我需要测试这个函数:
//user.js
function getUser(req, res, next){
helper.get_user(param1, param2, (err, file) => {
if (err) return next(err);
}这是我的测试函数:
it ("failed - helper.get_user throws error", sinon.test(function () {
var req, res;
var get_user = this.stub(helper, "get_user")
get_user.yields(new Error("message"));
var next = sinon.spy(next);
user.get_user(req, res, next);
expect(next).to.have.been.calledWith(new Error("other message"));
}))对于我的断言,我使用了sinon-chai语法。
这个测试正在通过,尽管我预计它会失败,因为我的代码没有抛出错误消息。
如何用正确的消息测试抛出的错误?
发布于 2017-05-04 05:31:14
我通常做的是:
const next = stub();
someMiddleware(req, res, next);
expect(next).to.have.been.called();
const errArg = next.firstCall.args[0];
expect(errArg).to.be.instanceof(Error);
expect(errArg.message).to.equal("Your message");请注意,我使用dirty-chai是为了对eslint友好。
HTH,
发布于 2018-06-20 00:51:06
由于您使用的是Sinon,因此还可以利用matchers。例如:
const expectedErr = { message: 'Your message' }
sinon.assert.calledWith(next, sinon.match(expectedErr))这将针对普通对象进行检查。更精确的检查应该是
const expectedErr = sinon.match.instanceOf(Error)
.and(sinon.match.has('message', 'Your message'))
sinon.assert.calledWith(next, sinon.match(expectedErr))有关更多详细信息,请查看this GitHub issue。
发布于 2021-09-04 00:37:38
一个更完整的示例来补充@Alex响应:
expect(next).to.have.been.calledWith(
sinon.match.instanceOf(Error)
.and(sinon.match.has(
'message',
'Some message',
)
)
);https://stackoverflow.com/questions/42119260
复制相似问题