setup localStorage for testing React app with jest

Viewed 1187

I have created an empty application with create-react-app. it provides a test script at pckage.json and a sample App.test.js. at the first step, I want to set up the test environment according to the documentation of create-react-app. in my app I will use localStorage. let's say an action like below to be tested

export const cancel = () => {
  localStorage.removeItem("MyAppData");
  return { type: types.USER_CANCEL};
};

besides the enzyme part, it shows how to initialize localStorage. so I ended up with a setupTests.js file like

import { configure } from "enzyme";
import Adapter from "enzyme-adapter-react-16";
// react-testing-library renders your components to document.body,
// this will ensure they're removed after each test.
import "react-testing-library/cleanup-after-each";
// this adds jest-dom's custom assertions
import "jest-dom/extend-expect";

configure({ adapter: new Adapter() });

const localStorageMock = {
  getItem: jest.fn(),
  setItem: jest.fn(),
  clear: jest.fn()
};
global.localStorage = localStorageMock;

here if I do not import jest from jest or jest-dom or jest-enzyme, ESLinter shows an error in jest.fn() that jest is not defined. when I import and run yarn test I get

$ react-scripts test --env=jsdom
 FAIL  src\App.test.js
  ● Test suite failed to run

    TypeError: _jest2.default.fn is not a function

      at Object.<anonymous> (src/setupTests.js:15:27)
          at <anonymous>

I really dont get from QAs here and in other forums how should I setup localStorage for testing.

2 Answers

You should not need to import jest into your test files.

You should instead tell eslint what Environment it should expect in the file so it knows what globals are present.

Add this to the top of any files where you use jest globals

/* eslint-env jest */

I really do not know what exactly happened, some packages related to jest, jet-dom, jest-enzyme was mkaing a conflict. but I managed to make it work after deleting package-lock.json, yarn.lock, node_modules, removing jest from the dependencies in package.json, then doing npm install and yarn install!

Related