Sinon-chai 使用 new Error() 和准确的错误信息进行调用。

13

我需要测试这个函数:

   //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语法。

尽管我希望代码会出错,但这个测试通过了,因为我的代码没有抛出带有错误信息的消息。

如何测试是否抛出了正确消息的错误?


请检查一下我的答案是否符合您的要求,并接受它。谢谢。 - Danosaure
3个回答

14

因为您正在使用Sinon,您还可以利用匹配器。例如:

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))

请查看此GitHub问题以获取更多详细信息。


我同意@ChrisSharp的观点,这是更好的答案。 - siyb

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的要求。
祝好,

1

为了补充@Alex的回答,以下是一个更完整的示例:

expect(next).to.have.been.calledWith(
  sinon.match.instanceOf(Error)
    .and(sinon.match.has(
      'message',
      'Some message',
    )
  )
);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接