sinon calledWith(new Error()) and with exact message

纵饮孤独 提交于 2020-01-24 04:28:13

问题


i need to test this function :

//user.js
function getUser(req,res,next){
helper.get_user(param1, param2, (err,file)=>{
        if (err)
            return next(err);}

my test function :

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

}))

for my assertion I'm using sinon-chai syntax. this test is passing even though i would expect it to fail. because my code doesn't throw message with the error.

how can i test that an error is thrown with correct message?


回答1:


What I usually do is:

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

Note that I am using dirty-chai to be eslint friendly.

HTH,




回答2:


Since you are using Sinon, you could also take advantage of the matchers. For example:

const expectedErr = { message: 'Your message' }

sinon.assert.calledWith(next, sinon.match(expectedErr))

This will check against a plain object. A more precise check would be

const expectedErr = sinon.match.instanceOf(Error)
  .and(sinon.match.has('message', 'Your message'))

sinon.assert.calledWith(next, sinon.match(expectedErr))

Check out this GitHub issue for more details.



来源:https://stackoverflow.com/questions/42119260/sinon-calledwithnew-error-and-with-exact-message

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!