Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

rejects.toMatchObject(new Error(...)) always passes #3795

Closed
dandv opened this issue Jun 12, 2017 · 2 comments
Closed

rejects.toMatchObject(new Error(...)) always passes #3795

dandv opened this issue Jun 12, 2017 · 2 comments

Comments

@dandv
Copy link
Contributor

dandv commented Jun 12, 2017

Can't post a repl.it because it doesn't run Jest v20+, so here's the code using Promises and rejecting with Error objects (a recommended pattern).

function foo() {
  return new Promise(function (resolve, reject) {
    reject(new Error('bar'));
  });
}

test('rejection 1', () => {
  expect.assertions(1);
  return expect(foo()).rejects.toMatchObject(new Error('totally different'));  // passes!
});

I would expect the test above to fail.

It would also be nice to document how to test for rejection with specific error messages. return expect(foo()).rejects.toEqual('bar'); errors out:

expect(received).toEqual(expected)
    
Expected value to equal:
  "bar"
Received:
  [Error: bar]

Difference:

  Comparing two different types of values. Expected string but received object.

This works:

return expect(foo()).rejects.toEqual(new Error('bar'));

but the Note at the end of the toEqual(value) docs recommends against using it for Error objects and toEqual can be too strict when ideally you'd check for a Regexp.

@thymikee
Copy link
Collaborator

You can use toEqual to test Errors if that works for you.
However what this issue shows is that toMatchObject is not checking if the object is error, which can lead to hard-to-track bugs, like this one.
Example can be shortened to:

test('toMatchObject passes on different Errors', () => {
  expect(new Error('foo')).toMatchObject(new Error('bar'));
});

I'll close this and open new issue just for toMatchObject.

@github-actions
Copy link

This issue has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.
Please note this issue tracker is not a help forum. We recommend using StackOverflow or our discord channel for questions.

@github-actions github-actions bot locked as resolved and limited conversation to collaborators May 13, 2021
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

No branches or pull requests

2 participants