How To Unit Test A Function Which Calls Another That Returns A Promise?
Solution 1:
You should move your assert section into the res.send
method to make sure all async tasks are done before the assertions:
var response = {
status: () => { return response; },
send: () => {
try {
// Assertexpect(findAllStub.called).to.be.ok;
expect(findAllStub.callCount).to.equal(1);
expect(response.status).to.be.calledWith(200); // not working// expect(response.send).to.be.called; // not needed anymore
done();
} catch (err) {
done(err);
}
},
};
Solution 2:
The idea here is to have the promise which service.findAll()
returns accessible inside the test's code without calling the service
. As far as I can see sinon-as-promised
which you probably use does not allow to do so. So I just used a native Promise
(hope your node version is not too old for it).
const aPromise = Promise.resolve(expectedCategories);
var findAllStub = sandbox.stub(service, 'findAll');
findAllStub.returns(aPromise);
// response = { .... }
controller.findAll({}, response);
aPromise.then(() => {
expect(response.status).to.be.calledWith(200);
expect(response.send).to.be.called;
});
Solution 3:
When code is difficult to test it can indicate that there could be different design possibilities to explore, which promote easy testing. What jumps out is that service
is enclosed in your module, and the dependency is not exposed at all. I feel like the goal shouldn't be to find a way to test your code AS IS but to find an optimal design.
IMO The goal is to find a way to expose service
so that your test can provide a stubbed implementation, so that the logic of findAll
can be tested in isolation, synchronously.
One way to do this is to use a library like mockery
or rewire
. Both are fairly easy to use, (in my experience mockery starts to degrade and become very difficult to maintain as your test suite and number of modules grow) They would allow you to patch the var service = require('./category.service');
by providing your own service object with its own findAll
defined.
Another way is to rearchitect your code to expose the service
to the caller, in some way. This would allow your caller (the unit test) to provide its own service
stub.
One easy way to do this would be to export a function contstructor instead of an object.
module.exports = (userService) => {
// default to the required servicethis.service = userService || service;
this.findAll = (request, response) => {
this.service.findAll().then((categories) => {
response.status(200).send(categories);
}, (error) => {
response.status(error.statusCode || 500).json(error);
});
}
};
varServiceConstructor = require('yourmodule');
var service = newServiceConstructor();
Now the test can create a stub for service
and provide it to the ServiceConstructor
to exercise the findAll
method. Removing the need for an asynchronous test altogether.
Post a Comment for "How To Unit Test A Function Which Calls Another That Returns A Promise?"