0

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?

1 Answer 1

1

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)
  });

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.