Chai: assert error objects

Created on 29 May 2012  路  4Comments  路  Source: chaijs/chai

I have a function that is passing an error object to it's callback:

function createUser (callback) {
  callback(new Error('user exists'));
}

createUser(function (err) {
  expect(err.message).to.equal('user exists')
});

I need to assert that the error is passed.

Is that the best way to do this?

Feel hacky in a way.

Most helpful comment

@johnnywengluu Were you able to accomplish what you were setting out to do.

As a side note, you can also do the following:

expect(err).to.exist
  .and.be.instanceof(Error)
  .and.have.property('message', 'user exists');

Though, I do agree with @domenic ... if you are doing a lot of this kind of checking you should make it easier on yourself and include the spy libraries.

All 4 comments

It sounds like you're trying to test that a function is invoked with a certain value. That's not entirely within Chai's domain, but more in the domain of a spy library like Sinon.JS. You can use Sinon with the Sinon鈥揅hai plugin to get a pretty nice syntax for making assertions about spy calls:

var spy = sinon.spy();
createUser(spy);

expect(spy).to.have.been.calledWith(new Error("user exists"));

// without Sinon鈥揅hai:
expect(spy.calledWith(new Error("user exists"))).to.be.ok;

@johnnywengluu Were you able to accomplish what you were setting out to do.

As a side note, you can also do the following:

expect(err).to.exist
  .and.be.instanceof(Error)
  .and.have.property('message', 'user exists');

Though, I do agree with @domenic ... if you are doing a lot of this kind of checking you should make it easier on yourself and include the spy libraries.

Nice example.

Right now your code will do it, but I'll look into why I might want to use spy.

Thanks a lot.

Johnny

Sent from my iPad

On 4 jun 2012, at 00:28, Jake [email protected] wrote:

@johnnywengluu Were you able to accomplish what you were setting out to do.

As a side note, you can also do the following:

expect(err).to.exist
 .and.be.instanceof(Error)
 .and.have.property('message', 'user exists');

Though, I do agree with @domenic ... if you are doing a lot of this kind of checking you should make it easier on yourself and include the spy libraries.


Reply to this email directly or view it on GitHub:
https://github.com/chaijs/chai/issues/70#issuecomment-6089679

Great. Let us know if you have any more questions.

Closing.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

zzzgit picture zzzgit  路  3Comments

meeber picture meeber  路  4Comments

liborbus picture liborbus  路  4Comments

AnAppAMonth picture AnAppAMonth  路  3Comments

basherr picture basherr  路  4Comments