12
votes

I was running my test suite for my react-native application with the command jest.

The tests would fail in the file jest-runtime/build/index.js on the line

const wrapper = this._environment.runScript(transformedFile.script)[
(_script_transformer || _load_script_transformer()).default.EVAL_RESULT_VARIABLE];

with the error:

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

My version of jest is 21.2.1.

Anyway, after some googling, I found that someone was running jest --env=jsdom. I gave that a try and then my test suite started working.

But what does this option mean?

I know that jsdom is an implementation of the DOM and HTML standards.

But how is this useful to jest? How does this change the behaviour of jest such that now the tests pass?

1
Do you override somewhere the testEnvironment property? jestjs.io/docs/en/configuration#testenvironment-string. This would change the default jsdom library used. CLI has higher precedence and would override the value and make it work. Jsdom is required, as it is the headless browser used for testing components.Jonathan Hamel
If you work in react it updates the vritual dom, not the real dom. Jest works without react this I think it's just extra info for what dom to read from. I can't however say this with being a 100% certain..Xorifelse

1 Answers

19
votes

Because jest is a node module and is executed on your local machine (or in a CI environment) and not in the browser, it runs in a node context. This means that globals that you can access inside a browser context, such as window or document are not available. So if you access these global objects inside your code (or any other browser specific feature, such as localStorage for example) your tests will have to fail. The option --env=jsdom ensures that a mock browser environment is provided to your tests and thus allows them to pass.