1

This is a follow-up question to this question:

I don't only want to test if the function throws an error but also if the thrown error has the same Error Message. So i tried:

expect(Person.getPerson.bind(Person, id)).to.throw(new Error(`Person ${id} not found`));

inside the getPerson function an Error is thrown lilke this:

if (!isPersonExistent(id)) {
   throw new Error(`Person ${id} not found`);
}

and the given message looks like this:

AssertionError: expected [Function: bound getPerson] to throw 'Error: Person 1 not found' but 'Error: Person 1 not found' was thrown

I guess it has something to do with the two error objects being two different objects. But how do I also test if they have the same error message. Optimally all in one step.

tamara d
  • 320
  • 5
  • 18

2 Answers2

2

You are correct that your assertion is failing because Chai .throw is comparing error objects by strict equality. From the spec:

When one argument is provided, and it’s an error instance, .throw invokes the target function and asserts that an error is thrown that’s strictly (===) equal to that error instance.

The same spec explains:

When two arguments are provided, and the first is an error instance or constructor, and the second is a string or regular expression, .throw invokes the function and asserts that an error is thrown that fulfills both conditions as described above.

where

.throw invokes the target function and asserts that an error is thrown with a message that contains that string.

So the way to test the desired behavior is using two arguments like this:

expect(Person.getPerson.bind(Person, id)).to.throw(Error, `Person ${id} not found`);
GOTO 0
  • 42,323
  • 22
  • 125
  • 158
0

Try this:

try {
  Person.getPerson(id);
} catch (error) {
  expect(error.message).to.be('Error: Person 1 not found');
  return;
}
expect.fail('Should have thrown');
Christian
  • 7,433
  • 4
  • 36
  • 61