jest: Using jest with node assert got wrong error type.

🐛 Bug Report

The assert module in nodejs will throw error when assertion fail. It will throw a AssertionError If the second parameter is a string. But if the second parameter is an instance of Error, it will throw it instead of AssertionError.

I’ve tried this code and got the expected error.

const assert = require('assert');
const err = new Error('error message');

assert.ok(false, err);

But in my test case, i got an AssertionError.

To Reproduce

You may run this test case, it will fail:

const assert = require('assert');
const err = new Error('error message');

test('assert error object', () => {
  expect(() => {
    assert.ok(false, err);
  }).toThrow(err);
});

The failed error message is:

image

Expected behavior

Pass the test case. I know i could use something like .toThrow(err.message) to pass it, but i want to check the error type also.

Link to repl or repo (highly encouraged)

Just run the case above. 😃

Run npx envinfo --preset jest

Paste the results here:

  System:
    OS: macOS 10.14.1
    CPU: (8) x64 Intel(R) Core(TM) i7-4980HQ CPU @ 2.80GHz
  Binaries:
    Node: 11.5.0 - ~/.nvm/versions/node/v11.5.0/bin/node
    npm: 6.4.1 - ~/.nvm/versions/node/v11.5.0/bin/npm
  npmPackages:
    jest: ^23.6.0 => 23.6.0

About this issue

  • Original URL
  • State: open
  • Created 6 years ago
  • Reactions: 13
  • Comments: 18 (3 by maintainers)

Most upvoted comments

I confirm this behavior.

This is a burden in one of our use cases as we use assert for tasks unrelated to unit testing. Jest having unexpected side effect on the assert lib wherever it is used makes it unreliable as a unit testing framework in our case.

I find it quite worrying that when I am running the code in the test environment it is being handled differently than it would in production. I should be able to rely on the fact my code will run the same in both environments otherwise the tests can’t really be trusted.

Are there any news on this issue? I just ran into the same problem and I’d hate to write my own assert function just to work around a longstanding bug in Jest.

👍 Also keen on a solution here.

It took me 30 minutes of googling just to find this thread. Why would the library override default assert and don’t even mention it anywhere in the docs?

Does anybody have a workaround for this problem ? (One that does not involve using a different assertion library in the base code)

Same thing here, I’m using the node’s assert function to do some assertions unrelated to unit testing and this behaviour causes the custom Error class to be substituted with the AssertionError. Because of this, all custom fields get lost.

Yeah, but that shouldn’t happen when I catch it locally, unless we inject a fake assert module?