Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

RCA jest setting for localStorage #4991

Closed
AmirHMousavi opened this issue Sep 10, 2018 · 2 comments
Closed

RCA jest setting for localStorage #4991

AmirHMousavi opened this issue Sep 10, 2018 · 2 comments

Comments

@AmirHMousavi
Copy link

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",

@AmirHMousavi
Copy link
Author

Ooops, it was making me crazy, I had to have const localStorageMock = {removeItem: jest.fn()

@phacks
Copy link
Contributor

phacks commented Nov 28, 2018

I suggested a change to add removeItem directly in the docs, see #5919. It think it could have saved you some time 🙂

@lock lock bot locked and limited conversation to collaborators Jan 9, 2019
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants