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

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

Closed
jtulk opened this issue Oct 16, 2017 · 31 comments
Closed

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

jtulk opened this issue Oct 16, 2017 · 31 comments

Comments

@jtulk
Copy link

jtulk commented Oct 16, 2017

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"
  }
@jtulk
Copy link
Author

jtulk commented Oct 16, 2017

I've found similar errors in other places: https://www.google.com/search?q=jest+Cannot+read+property+%27Object.%3Canonymous%3E%27+of+null&rlz=1C5CHFA_enUS703US703&oq=jest+Cannot+read+property+%27Object.%3Canonymous%3E%27+of+null&aqs=chrome..69i57j69i60l3j0l2.931j0j4&sourceid=chrome&ie=UTF-8 but have not found any posted resolution. If anyone is aware of a resolution please link and I'll close.

@silverlight513
Copy link

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.

@silverlight513
Copy link

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

  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.<anonymous>.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)```

@jtulk jtulk changed the title TypeError: Cannot read property 'Object.<anonymous>' of null on 21.2.1 TypeError: Cannot read property 'Object.<anonymous>' of null Oct 17, 2017
@SimenB
Copy link
Member

SimenB commented Oct 21, 2017

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

@silverlight513
Copy link

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.

@SimenB
Copy link
Member

SimenB commented Oct 23, 2017

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...

@jtulk
Copy link
Author

jtulk commented Oct 24, 2017

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.

@silverlight513
Copy link

@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.

@SimenB
Copy link
Member

SimenB commented Oct 24, 2017

@silverlight513 did you return the result from supertest?

@silverlight513
Copy link

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

@SimenB
Copy link
Member

SimenB commented Oct 24, 2017

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.

@silverlight513
Copy link

silverlight513 commented Oct 24, 2017

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;
    });
});

@jtulk
Copy link
Author

jtulk commented Oct 31, 2017

@SimenB Deeper digging is making me think this is actually related to #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

@silverlight513
Copy link

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.

@SimenB
Copy link
Member

SimenB commented Nov 1, 2017

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

@theoutlander
Copy link

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. :|

@fudanchii
Copy link

fudanchii commented Nov 25, 2017

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.

@cpojer
Copy link
Member

cpojer commented Dec 15, 2017

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.

@cpojer cpojer closed this as completed Dec 15, 2017
@matt-oakes
Copy link

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.

@colorfulberry
Copy link

colorfulberry commented Mar 7, 2018

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()
        }
      },
    }),
  }
})

@yuhr
Copy link

yuhr commented Mar 28, 2018

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

@SimenB
Copy link
Member

SimenB commented Mar 28, 2018

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

@yuhr
Copy link

yuhr commented Mar 29, 2018

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

@mrruby
Copy link

mrruby commented May 23, 2018

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

@SimenB
Copy link
Member

SimenB commented May 23, 2018

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!

@jaulz
Copy link

jaulz commented May 24, 2018

@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'

@ryanbrainard
Copy link

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.

@hnrchrdl
Copy link

hnrchrdl commented Aug 3, 2018

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.

@martabacc
Copy link

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?)?

@youngjuning
Copy link

@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

@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 11, 2021
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests