我有一个使用express 4的node.js应用程序,这是我的控制器:
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);
});
}
};
它调用我的服务并返回一个承诺。一切正常,但我在尝试对其进行单元测试时遇到了麻烦。
基本上,我想确保根据我的服务返回的内容,我使用正确的状态代码和正文刷新响应。
因此,对于摩卡和 sinon 来说,它看起来像:
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();
});
当我正在测试的函数返回一个承诺时,我已经测试了类似的场景,因为我可以在那时挂钩我的断言。
我还尝试用 Promise 包装controller.findAll,并从response.send 解析它,但它也不起作用。