Abed Nego Lubis
Abed Nego Lubis

Reputation: 91

How to test localStorage in my react app?

I have a private route in my react app, and when I use jest and run yarn test to test my app, and it shows that in my PrivateRoute file there's one line without coverage. It's line 8 in the localStorage.getItem code,

enter image description here

How do I get coverage for that line?

Upvotes: 3

Views: 11138

Answers (3)

Karen Grigoryan
Karen Grigoryan

Reputation: 5432

Put this in your test initializer files:

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

global.localStorage = localStorageMock;

So now you can just use localStorageMock globally

expect(localStorageMock.getItem).toHaveBeenCalledWith('access_token')

The only gotcha is to make sure that your tests have jest.clearAllMocks() cleanup step so the mock is reinitialized for other tests.

Upvotes: 0

Estus Flask
Estus Flask

Reputation: 222989

localStorage.getItem should be spied before expected call:

jest.spyOn(localStorage, 'getItem');

And asserted that it was called afterwards:

expect(localStorage.getItem).toBeCalledWith('access_token');

Upvotes: 0

Mitul Marsoniya
Mitul Marsoniya

Reputation: 5299

You can use like this:-

const result = '{ "name":"John", "age":30, "car":"bmw"}';

//set json object to storage 
localStorage.setItem('user', JSON.stringify(result));

//get object
const value = localStorage.getItem('user');

//remove object
localStorage.removeItem('user');

Upvotes: 0

Related Questions