Jest: TypeError: Cannot read property 'Object.<anonymous>' of null

Created on 16 Oct 2017  路  30Comments  路  Source: facebook/jest

Trying to run Jest tests after upgrading.

/Users/justintulk/Sites/myProject/node_modules/jest-runtime/build/index.js:518
    (_script_transformer || _load_script_transformer()).default.EVAL_RESULT_VARIABLE];

TypeError: Cannot read property 'Object.<anonymous>' of null

Do you want to request a feature or report a bug?

Report a bug.

What is the current behavior?

yarn test fails at running scripts/test.js (included). Throws primarily when trying to run _all_ the tests, running yarn watch and only testing changed files has not reproduced the errors.

/Users/justintulk/Sites/myProject/node_modules/jest-runtime/build/index.js:518
    (_script_transformer || _load_script_transformer()).default.EVAL_RESULT_VARIABLE];
                                                               ^
TypeError: Cannot read property 'Object.<anonymous>' of null
    at Runtime._execModule (/Users/justintulk/Sites/myProject/node_modules/jest-runtime/build/index.js:518:64)
    at Runtime.requireModule (/Users/justintulk/Sites/myProject/node_modules/jest-runtime/build/index.js:332:14)
    at Runtime.requireModuleOrMock (/Users/justintulk/Sites/myProject/node_modules/jest-runtime/build/index.js:408:19)
    at Object.getVendors (/Users/justintulk/Sites/myProject/node_modules/newrelic/lib/utilization/index.js:6:10)
    at fetchSystemInfo (/Users/justintulk/Sites/myProject/node_modules/newrelic/lib/system-info.js:93:15)
    at facts (/Users/justintulk/Sites/myProject/node_modules/newrelic/lib/collector/facts.js:9:3)
    at _getFacts (/Users/justintulk/Sites/myProject/node_modules/newrelic/lib/collector/api.js:162:5)
    at redirectCb (/Users/justintulk/Sites/myProject/node_modules/newrelic/lib/collector/api.js:158:5)
    at cb_nextTick (/Users/justintulk/Sites/myProject/node_modules/newrelic/lib/collector/parse-response.js:113:7)
    at _combinedTickCallback (internal/process/next_tick.js:131:7)
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.

If the current behavior is a bug, please provide the steps to reproduce and either a repl.it demo through https://repl.it/languages/jest or a minimal repository on GitHub that we can yarn install and yarn test.

What is the expected behavior?

Should run tests without crashing.

Please provide your exact Jest configuration and mention your Jest, node, yarn/npm version and operating system.

EDIT ~Works fine~ fails w/ Jest 20.0.4
Fails on 21.2.1

scripts/test.js

// Do this as the first thing so that any code reading it knows the right env.
process.env.BABEL_ENV = "test";
process.env.NODE_ENV = "test";
process.env.PUBLIC_URL = "";

// Makes the script crash on unhandled rejections instead of silently
// ignoring them. In the future, promise rejections that are not handled will
// terminate the Node.js process with a non-zero exit code.
process.on("unhandledRejection", err => {
  throw err;
});

const ijest = require("jest");

const argv = process.argv.slice(2);

// Watch unless on CI or in coverage mode
// if (!process.env.CI && argv.indexOf("--coverage") < 0) {
//   argv.push("--watch");
// }

ijest.run(argv);

Package.json

  "test": "node scripts/test.js",
  "jest": {
    "collectCoverageFrom": ["src/**/*.{js,jsx}"],
    "testMatch": [
      "<rootDir>/controllers/**/__tests__/**/*.js?(x)",
      "<rootDir>/controllers/**/?(*.)(spec|test).js?(x)"
    ],
    "testEnvironment": "node",
    "testURL": "http://localhost",
    "testResultsProcessor": "./node_modules/jest-junit"
  }

Most helpful comment

For the Animated problem, Can add this to your test file

jest.mock('Animated', () => {
  const ActualAnimated = require.requireActual('Animated')
  return {
    ...ActualAnimated,
    timing: (value, config) => ({
      start: callback => {
        value.setValue(config.toValue)
        if (callback) {
          callback()
        }
      },
    }),
  }
})

All 30 comments

I am getting the same error on 20.0.4 and can't find a way to shake the error. The tests were passing before I did a yarn install.

If I switch my test environment from node to the default jsdom I get the following error instead

```/project/node_modules/negotiator/index.js:57
return preferredEncodings(this.request.headers['accept-encoding'], available);
^

TypeError: preferredEncodings is not a function
at Negotiator.encodings (/project/node_modules/negotiator/index.js:57:10)
at Accepts.Object..Accepts.encoding.Accepts.encodings (/project/node_modules/accepts/index.js:136:26)
at ServerResponse.onResponseHeaders (/project/node_modules/compression/index.js:178:27)
at ServerResponse.writeHead (/project/node_modules/on-headers/index.js:46:16)
at ServerResponse._implicitHeader (_http_server.js:179:8)
at ServerResponse.end (/project/node_modules/compression/index.js:103:14)
at Array.write (/project/node_modules/finalhandler/index.js:266:9)
at listener (/project/node_modules/on-finished/index.js:169:15)
at onFinish (/project/node_modules/on-finished/index.js:100:5)
at callback (/project/node_modules/ee-first/index.js:55:10)
at IncomingMessage.onevent (/project/node_modules/ee-first/index.js:93:5)
at emitNone (events.js:105:13)
at IncomingMessage.emit (events.js:207:7)
at endReadableNT (_stream_readable.js:1059:12)
at _combinedTickCallback (internal/process/next_tick.js:138:11)
at process._tickDomainCallback (internal/process/next_tick.js:218:9)```

Can anyone provide a reproduction? I've come across this myself, but I can't seem to reproduce it now. A repro will go a long way towards helping us come up with a fix

After fixing the error within one of the my projects I think I've got a theory as to why the error appears.

Just to make sure it wasn't my machine I ran tests in an isolated jenkins job. The exact same error appeared. This ruled out that it was something specific with my laptop. From there I started to replicate tests manually and found that jest claimed that tests were passing when the functions and endpoints were actually error'ing out. This lead me to fixing bugs in my code that were producing 500 errors on endpoints and undefined errors in functions.

After I fixed all the errors in my code the tests were passing completely fine. This leads me to believe that jest falls over when it encounters an error with an asynchronous test.

I'll try and create a reproduction sometime soon but I'm not sure when I'll have time outside of work.

What I observed was that the error came up after not awaiting an asynchronous operation. My theory was is that the cleanup (dispose) of the test environment was called before some code tried to access something that was garbage collected.

I'm unable to reproduce, though...

I haven't been able to confirm anything more on my side about what causes it, but the async stuff sounds like it's on the right track to me. It's happening in one of my repos where I'm testing real async functions (not mocks) and using beforeAll and afterAll to stage and clean up changes. It's _not_ happening in a different repo where I don't have any async tests that aren't mocked.

Our CI (CircleCI) is running fine, so I wonder if this is in some way related to the watch mode.

@jtulk, I've never used watch mode and I've also never used any clean up methods. I was using nothing but describe and it functions. The tests that were failing (but not showing as failed) were async tests that use supertest to hit endpoints.

@silverlight513 did you return the result from supertest?

Nope, the result doesn't serialize as far as I'm aware. I'd just call expect and finally the done function in the .then

Ah, you called done, that should work.

I meant that supertest returns a promise, which can be returned directly to jest.

test('some stuff', () => {
  return supertest(app)
    .get('/')
    .expect(200);
})

You don't need the done callback.

Yeah, I just preferred using the done method as I had a problem in the past returning promises with async tests. Might have been back when I was using mocha but it's just become a habit.

I assumed you meant this

it('will respond with a success', done => {
  supertest(app)
    .get('/')
    .then(res => {
      expect(res.statusCode).toBe(200);
      done();
      return res;
    });
});

@SimenB Deeper digging is making me think this is actually related to https://github.com/facebook/jest/issues/2605 for me. As far as I can tell the error is thrown when using the New Relic node library: https://github.com/newrelic/node-newrelic

I'm not so sure, the only modules I was using were supertest, superagent and express when I was running into the errors. I think the problem we've been experiencing is probably something to do with how jest handles async bugs in code. Some of bugs those bugs could come from other modules like node-newrelic and iconv-lite.

Even if it does come down to purely an issue with other modules, Jest shouldn't show an unhelpful error and should try and send a meaningful error message.

I think the issue is that we return null from the test environment if it's been GC-ed instead of throwing a more explicit error.

Can send a PR for what I think will be a better error, but it would be great if we could get a reproduction to test it on

I had this very issue, but it was sporadic. It was caused by opbeat, but I think it also had someting to do with creating a global.window object in my setup test file. Removing opbeat has fixed the issue for me. :|

It's been broken consistently in my circle CI (jest running inside docker container with node:8.9.0 image, also tested with node:8.9.1 same error).

The test run without a hitch in my local machine (even with the same setup as circle CI i.e. run in docker and node:8.9.0).

But since it's always errored in the CI, I think I can test something in case anyone has any suggestion.

Here's the log from jest:

/src/core-ui/node_modules/jest-runtime/build/index.js:517
    const wrapper = this._environment.runScript(transformedFile.script)[
                                                                       ^

TypeError: Cannot read property 'Object.<anonymous>' of null
    at Runtime._execModule (/src/core-ui/node_modules/jest-runtime/build/index.js:517:72)
    at Runtime.requireModule (/src/core-ui/node_modules/jest-runtime/build/index.js:332:14)
    at Runtime.requireModuleOrMock (/src/core-ui/node_modules/jest-runtime/build/index.js:408:19)
    at WatcherManager.Object.<anonymous>.WatcherManager.getDirectoryWatcher (/src/core-ui/node_modules/watchpack/lib/watcherManager.js:12:25)
    at WatcherManager.watchFile (/src/core-ui/node_modules/watchpack/lib/watcherManager.js:26:14)
    at Watchpack.<anonymous> (/src/core-ui/node_modules/watchpack/lib/watchpack.js:36:49)
    at Array.map (<anonymous>)
    at Watchpack.watch (/src/core-ui/node_modules/watchpack/lib/watchpack.js:35:28)
    at NodeWatchFileSystem.watch (/src/core-ui/node_modules/webpack/lib/node/NodeWatchFileSystem.js:51:16)
    at Watching.watch (/src/core-ui/node_modules/webpack/lib/Compiler.js:115:48)
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
exit status 1

Seems like coming from webpack there. ~But why it's only error on the CI is a mystery~.


update:

After some tests I figure out that I can replicate the error in my local machine by running jest with -w 1
this explains why it's only error at circle CI, they seems to gave only 1 vcpu for each build env.

I only have __tests__ folders under these directories:

src/app
src/contexts
src/layouts

and jest only error if it's running all tests at once, it wont error when running with any combination of two folders, or if it's only one of them e.g. jest src/app

For workaround I separate the tests into two jest calls: jest src/app and jest src/contexts src/layouts.

This will fail in Jest 22 because we clean up the contexts more aggressively. This error normally happens when you are scheduling async work after the test run for a file has already been completed.

For others that find this issue, it can be caused by running an Animated animation in React Native. Not running that animation when jest is detected is the best solution I found for now.

For the Animated problem, Can add this to your test file

jest.mock('Animated', () => {
  const ActualAnimated = require.requireActual('Animated')
  return {
    ...ActualAnimated,
    timing: (value, config) => ({
      start: callback => {
        value.setValue(config.toValue)
        if (callback) {
          callback()
        }
      },
    }),
  }
})

Using js-ipfs seems to cause this error but I can't find out why this happens actually

I've opened up a PR trying to give a better error in this situation: #5888

Ah I overlooked... done callback should work. Thanks for the informative error text.

Change react-test-renderer to e.g. enzyme

For people getting this, please try the Jest 23 beta (yarn add --dev jest@beta) which includes the PR I opened above. It should hopefully help!

@SimenB that error message helps a lot - thanks!
for anyone stumbling across this issue with Animated, put the following line into the jest setup script:
import 'react-native/Libraries/Animated/src/bezier'

None of the above fixes worked for me. While certainly not ideal, a simple workaround is adding setImmediate(done); to the end of the test.

In my case this issue was caused by the autofocus prop on react-native's TextInput component. I am on jest@22. I tested again with jest@23 and can confirm this issue is resolved.

For anyone still in need for a fix for this, see this comment on how to mock the TextInput.

hi @hnrchrdl, however I got an issue when I implemented the quickfix.

The testcase seems like never ended. Is this also happened to you? What did you put on the afterEach block to reset the TextInput (or is it necessary?)?

@SimenB that error message helps a lot - thanks!
for anyone stumbling across this issue with Animated, put the following line into the jest setup script:
import 'react-native/Libraries/Animated/src/bezier'

Thanks a lot

Was this page helpful?
0 / 5 - 0 ratings