Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

148
Views
How do I configure jsdom with jest

I have installed jest and jsdom into my react project but I am having problems with importing a react component that uses the window.localStorage variable. I have added a setup file for jsdom that I believed would solve the problem.

Here is my setup:

jest config in package.json

"jest": {
    "verbose": true,
    "testEnvironment": "jsdom",
    "testURL": "http://localhost:8080/Dashboard/index.html",
    "transform": {
      "^.+\\.js$": "<rootDir>/node_modules/babel-jest",
      "^.+\\.jsx$": "<rootDir>/node_modules/babel-jest"
    },
    "unmockedModulePathPatterns": [
      "node_modules/react/",
    ],
    "moduleFileExtensions": [
      "js",
      "jsx",
      "json",
      "es6"
    ]
  }

setup.js

import jsdom from 'jsdom';

const DEFAULT_HTML = '<html><body></body></html>';

global.document = jsdom.jsdom(DEFAULT_HTML);

global.window = document.defaultView;
global.navigator = window.navigator;
global.localStorage = window.localStorage;

test.js

'use strict';
import setup from './setup';
import React from 'react';
import jsdom from 'jsdom';
import Reportlet from '../components/Reportlet.jsx';

it('Ensures the react component renders', () => {

});

My reportlet component uses the localStorage variable but yells:

Cannot read property getItem of undefined when I call localStorage.getItem(<some item>)

I read here that jest comes shipped with jsdom but I am not sure if I need the extra jsdom dependency or not. I also read here that jsdom needs to be loaded before requiring react for the first time.

Does anyone know how to configure jest with jsdom correctly?

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

jsdom does not support localStorage. It looks like you can use a node-friendly stub like 'node-localstorage'. See bottom of comments at https://github.com/tmpvar/jsdom/issues/1137

...or you can mock it with something like https://github.com/letsrock-today/mock-local-storage

...or roll your own mock like seen here: How to mock localStorage in JavaScript unit tests?

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!