Sinon-chai calledWith(new Error()) 和确切的消息



>我需要测试这个函数:

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

即使我希望它失败,此测试也会通过,因为我的代码不会抛出带有错误的消息。

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

由于您使用的是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 问题以获取更多详细信息。

我通常做的是:

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

请注意,我正在使用脏柴来对 eslint 友好。

呵呵,

一个更完整的示例来补充@Alex响应:

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

相关内容

最新更新