【发布时间】:2016-05-07 01:24:10
【问题描述】:
我正在尝试对使用 Promise 的 mongoose 对象进行单元测试。我已经编写了下面的测试,它可以工作,但它并不完整。我不知道如何测试是否调用了“then”或“catch”方法。
我如何使用 spy 来检查当我解决 promise 时是否调用了 'then' 方法?
测试方法
export function create(req, res) {
User
.createAsync(req.body)
.then(handleCreate(res, req.originalUrl))
.catch(handleError(res));
}
单元测试
it('should do something', () => {
const req = {
body: 45,
};
const res = {};
const mockRole = sandbox.mock(Role).expects('createAsync').once().withArgs(45)
.returns(Promise.resolve());
controller.create(req, res);
});
更新我使用的解决方案(2016 年 5 月 6 日)
感谢@ReedD 帮助我朝着正确的方向前进
虽然这“有效”,但我觉得我在测试 Promise 的功能而不是我的代码。
it('should call create with args and resolve the promise', () => {
const createSpy = sinon.spy();
const errorSpy = sinon.spy();
sandbox.stub(responses, 'responseForCreate').returns(createSpy);
sandbox.stub(responses, 'handleError').returns(errorSpy);
sandbox.mock(Role).expects('createAsync').once().withArgs(45)
.returns(Promise.resolve());
return controller.create(req, res).then(() => {
expect(createSpy.calledOnce).to.be.equal(true);
expect(errorSpy.calledOnce).to.be.equal(false);
});
});
【问题讨论】:
标签: node.js unit-testing mongoose bluebird es6-promise