I have a node.js application using express 4 and this is my controller:
var service = require('./category.service'); module.exports = { findAll: (request, response) => { service.findAll().then((categories) => { response.status(200).send(categories); }, (error) => { response.status(error.statusCode || 500).json(error); }); } };
It calls my service, which returns a promise. Everything works, but I am having trouble trying to unit test it.
Basically, I would like to make sure that depending on what my service returns, I clear the response with the correct status code and body.
So, with mocha and sinon, it looks something like this:
it('Should call service to find all the categories', (done) => { // Arrange var expectedCategories = ['foo', 'bar']; var findAllStub = sandbox.stub(service, 'findAll'); findAllStub.resolves(expectedCategories); var response = { status: () => { return response; }, send: () => {} }; sandbox.spy(response, 'status'); sandbox.spy(response, 'send'); // Act controller.findAll({}, response); // Assert expect(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 working done(); });
I tested my similar scenarios when the function I'm testing promises, as I can consolidate my statements at that time.
I also tried wrapping controller.findAll with a promise and resolving it from response.send, but it does not work either.
source share