Search code examples
sinonsinon-chai

sinon.js: fake.rejects - test with calledWith


i have a function, which looks for a user in a database - in this case i want to "reject", since the user is not found.

If no user is found, a callback is called with the rejection error and a second parameter (false)

return Login
  .findOne({
    where: {
      id: decoded.loginId,
      expireDate: {
        $gt: now,
      },
    },
  })
  .then(login => done(null, !!login))
  .catch(error => done(error, false));

I fake the findOne function to reject:

Login.findOne = sinon.fake.rejects(false);

How to check if my callback is called properly now?

// Inside validateToken the above code is implemented
const done = sinon.fake();
await validateToken({
  tokenInvalidate: moment().add(1, 'minute').toDate(),
  loginId: 1,
}, { server }, done);
done.should.be.calledWith(new Error(false), false);

I tried a lot of parameters, but it does not seem that i can find out what i should use as parameter here. Maybe i got the documentation wrong? I don't know... Thats the actual output:

 AssertionError: expected fake to have been called with arguments Error: false, false
Error: false
false

Modules:

"sinon": "^6.2.0",
"sinon-chai": "^3.2.0",

Thanks in advance


Solution

  • Figured out the issue...

    Had to use sinon.fake.rejects(errorInstance) instead of false or an inline created instance of an error.

    In the check i had to use the same instance:

    const error = new Error();
    Login.findOne = sinon.fake.rejects(error);
    done.should.be.calledWith(error, false);