简体   繁体   中英

Unit testing controller functions in Nodejs using Mocha and Chai

I have a function in my controller which takes 2 arguments request and response.

function convertTime (req, res) {
   callOtherFunction().then(function(result){
       res.status(200).send(result);
    }
}

My unit testing function to test this function looks something like this.

describe('Testing my function ', function() {
  var req = {
      query: {}
     };

 var res = {
     sendCalledWith: '',
     send: function(arg) { 
              this.sendCalledWith = arg;
            },
    json: function(err){
            console.log("\n : " + err);
            },
     status: function(s) {this.statusCode = s; return this;}
   };

  it('Should error out if no inputTime was provided', function() {
    convertTime(req,res);
    expect(res.statusCode).to.equal(500)
  });

});

when I run my unit testing, it's not waiting for my response to resolve. As I don't have a callback function here to wait for, how do I make the test to wait until res object is updated?

It's prefer to return promises from functions that use them. This is naturally done in async functions. Even if this isn't needed in production, this improves testability.

function convertTime (req, res) {
   return callOtherFunction().then(function(result){
       res.status(200).send(result);
    }

Then a promise can be chained:

  it('Should error out if no inputTime was provided', async function() {
    await convertTime(req,res);
    expect(res.statusCode).to.equal(500)
  });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM