Gambit2007
Gambit2007

Reputation: 3948

JavaScript - getting "res.json is not a function" error when testing with Mocha

I have the following function that i'm testing:

module.exports = {

    post: function myFunc(req, res) {
        some logic...
        ...
        ...
        res.json(ObjectToReturn);

}
}

And i'm trying to test in with Mocha like so:

  it("some test", function() {

      const response = myModule.post(
                           { reqPayLoad }, 
                           {}
                              );
      console.log(response)
  });

But i'm keep getting the error:

res.json is not a function

What am i doing wrong?

Upvotes: 0

Views: 811

Answers (1)

HMilbradt
HMilbradt

Reputation: 4639

The object literal being passed to post is empty: {},

In order to test this, you'd need to mock it out.

myModule.post(
    { reqPayLoad }, 
    { json: () => {} }
);

There's another problem here though. Your post method does not actually return anything, so response will be undefined.

Instead, res.json() is being called to send the data back to the client, so you're going to need to inspect what that's being called with.

You might modify the mocked json method to log the result:

myModule.post(
    { reqPayLoad }, 
    { json: data => console.log(data) }
);

In order to actually test the returned value of post though, you're probably going to need something like Sinon spies to let you inspect what res.json() is being called with programmatically.

let jsonSpy = sinon.spy();
myModule.post(
    { reqPayLoad }, 
    { json: jsonSpy }
);

assert(jsonSpy.calledWith(ObjectThatWasReturned));

Update

If the post method is asynchronous, you'll also need some way to wait for it to complete. In my opinion, the simplest way to do that is by using async/await

    // async makes the function return a promise
    post: async function myFunc(req, res) {
        some logic...
        ...
        ...
        res.json(ObjectToReturn);

}

Then, we await the promise inside the test:

  // Note: we set this function as async as well
  it("some test", async function() {

    let jsonSpy = sinon.spy();
    // wait for the promise to resolve
    await myModule.post(
        { reqPayLoad }, 
        { json: jsonSpy }
    );

    assert(jsonSpy.calledWith(ObjectThatWasReturned));
  });

Update Using Callbacks

Check out the Mocha docs on testing async code. Here's an example:

it("some test", function(done) {

    // wait for the promise to resolve
    await myModule.post(
        { reqPayLoad }, 
        { 
            json: returnObject => {
                assert(returnObject).toEqual('some_object')
                done()
            } 
    }
    );
  });

Upvotes: 2

Related Questions