Skip to content

Commit

Permalink
Don't format node assert errors when there's no 'assert' module (#4376)
Browse files Browse the repository at this point in the history
* Don't format node assert errors when there's no 'assert' module

In format_node_assert_errors.js, we require the 'assert' module to
detect that an error thrown is an AssertionError, so that we can format
assertion errors nicely. This creates an implicit dependency in the
library on the assert module (a node builtin, but not available without
adding a shim in browsers, React Native, etc).

If we are running in an environment where assert is not available, we
don't need to try to format assertion errors, so we can just bail.
Detecting this case and performing the require in a try/catch removes
the implicit dependency on assert.

Fixes #4365

* Use require.call(null, 'assert') instead of require('assert')

The React Native packager was attempting to pull in the assert module as a
dependency when using `require('assert')`, but it does not do this if you
use require.call(null, 'assert'), because it does not detect this pattern.

* Update format_node_assert_errors.js

* Remove unnecessary test
  • Loading branch information
suchipi authored and cpojer committed Aug 27, 2017
1 parent 51e0a24 commit dfdca8b
Showing 1 changed file with 15 additions and 1 deletion.
16 changes: 15 additions & 1 deletion packages/jest-circus/src/format_node_assert_errors.js
Original file line number Diff line number Diff line change
Expand Up @@ -43,8 +43,22 @@ module.exports = (event: Event, state: State) => {
switch (event.name) {
case 'test_failure':
case 'test_success': {
let assert;
try {
// Use indirect require so that Metro Bundler does not attempt to
// bundle `assert`, which does not exist in React Native.
// eslint-disable-next-line no-useless-call
assert = require.call(null, 'assert');
} catch (error) {
// We are running somewhere where `assert` isn't available, like a
// browser or React Native. Since assert isn't available, presumably
// none of the errors we get through this event listener will be
// `AssertionError`s, so we don't need to do anything.
break;
}

event.test.errors = event.test.errors.map(error => {
return error instanceof require('assert').AssertionError
return error instanceof assert.AssertionError
? assertionErrorMessage(error, {expand: state.expand})
: error;
});
Expand Down

0 comments on commit dfdca8b

Please sign in to comment.