Skip to content

RCA jest setting for localStorage #4991

Closed
@AmirHMousavi

Description

@AmirHMousavi

I have used CRA to create my app.
followed the setup for testing and created src/setupTests.js

import { configure } from "enzyme";
import Adapter from "enzyme-adapter-react-16";
import "react-testing-library/cleanup-after-each";
import "jest-dom/extend-expect";

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

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

in the src/actions/AllActions.js I have a function like

export const cancelGame = () => {
  localStorage.removeItem("BattleShipState");
  return { type: types.PLAYER_CANCELS_GAME };
};

and in src/actions/AllActions.test.js I want to test the function. (either I want to test the localStroage or not I get the same error).

test("Player cancels game", () => {
  const action = actions.cancelGame();
  expect(action).toEqual({
    type: types.PLAYER_CANCELS_GAME
  });
});

after running test I get

 FAIL  src\actions\AllActions.test.js
  ● Player cancels game

    TypeError: localStorage.removeItem is not a function

      at Object.<anonymous>.exports.cancelGame (src/actions/AllActions.js:35:16)
      at Object.<anonymous>.test (src/actions/AllActions.test.js:52:26)
          at new Promise (<anonymous>)
      at Promise.resolve.then.el (node_modules/p-map/index.js:46:16)
          at <anonymous>
      at process._tickCallback (internal/process/next_tick.js:188:7)

also, I have not touched the package.json and the test script is "test": "react-scripts test --env=jsdom",

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions