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?
jsdom is a pure JavaScript implementation of the DOM and browser APIs that runs in node. If you're not using Jest and you would like to run your tests in Node, then you must install jsdom yourself. There's also a package called global-jsdom which can be used to setup the global environment to simulate the browser APIs.
JSDOM is a library which parses and interacts with assembled HTML just like a browser. The benefit is that it isn't actually a browser. Instead, it implements web standards like browsers do. You can feed it some HTML, and it will parse that HTML.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With