Sinon-chai calledWith(new Error()) and with exact message
Asked Answered
F

3

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

This is 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 a message with the error.

How can I test that an error is thrown with correct message?

Fagoting answered 8/2, 2017 at 17:0 Comment(1)
Check if my answer is what you are looking for and accept it. Thanks.Ramonitaramos
R
14

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,

Ramonitaramos answered 3/5, 2017 at 21:31 Comment(0)
P
14

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.

Perforce answered 19/6, 2018 at 16:51 Comment(1)
I agree with @ChrisSharp, this is the better answerMello
A
1

A more complete example to complement @Alex response:

expect(next).to.have.been.calledWith(
  sinon.match.instanceOf(Error)
    .and(sinon.match.has(
      'message',
      'Some message',
    )
  )
);
Alburga answered 4/9, 2021 at 0:37 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.