I have a test that imports a component that in turn imports a helper file that uses the window object to pull out a query string parameter. I get the following error about window:
FAIL src/js/components/__tests__/Controls.test.jsx ● Test suite failed to run ReferenceError: window is not defined Controls.jsx:
import { Unwrapped as Controls } from '../Controls' describe('<MyInterestsControls />', () => { it('should render the component with the fixture data', () => { const component = shallow( <UnwrappedMyInterestControls dashboardData={dashboardData} loadingFlags={{ controls: false }} /> ) expect(component).toMatchSnapshot() }) }) Controls.jsx imports ./helpers/services.js which contains the following:
import * as queryString from 'query-string' const flag = queryString.parse(window.location.search).flag || 'off' ^^^^^^ this seems to be the problem I have attempted to import jsdom:
import { JSDOM } from 'jsdom' And implemented the solution presented here at the top of my test file:
const { JSDOM } = require('jsdom'); const jsdom = new JSDOM('<!doctype html><html><body></body></html>'); const { window } = jsdom; function copyProps(src, target) { const props = Object.getOwnPropertyNames(src) .filter(prop => typeof target[prop] === 'undefined') .map(prop => Object.getOwnPropertyDescriptor(src, prop)); Object.defineProperties(target, props); } global.window = window; global.document = window.document; global.navigator = { userAgent: 'node.js', }; copyProps(window, global); However, I still get the error and it seems JSDOM's window object isn't exposed to the test.
How can I properly expose global objects like window or document to a Jest test?
Relevant package.json
"scripts": { "test:watch": "NODE_ENV=test jest --watch" }, ... "devDependencies": { ... "jest": "^20.0.4", "jest-mock": "^21.2.0", "jsdom": "^11.0.0", ... }, ... "jest": { "verbose": true, "collectCoverageFrom": [ "src/js/helpers/preparePayload.js", "src/js/components-ni", "!**/node_modules/**", "!**/dist/**" ], "coverageThreshold": { "global": { "statements": 50, "branches": 50, "functions": 50, "lines": 75 } }, "testEnvironment": "jest-environment-node" }
package.json, by default jest uses thetestEnvironmentto browser-likejsdomso you don't have to importjsdomto your unit tests