How to test if localStorage receives item I set in a function?

Viewed 291

Currently trying to run a unit test for a authentication function. I've written a dummy function that basically does what the authentication function for the sake of abiding by NDA.

Authentication.js

export const myTestFunction = param => {
  console.log(param);
  localStorage.setItem("Test", param)
}

index.test.js

import {myTestFunction} from "../../redux/actions/ApiAuthAction";

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

test("Test to see myTestFunction sets localStorage to the param value", () => {
    let param = "Hello"
    myTestFunction(param);
    expect(localStorageMock.setItem).toBeCalledWith("Test");
});

When I run the test, this is what it returns:

expect(jest.fn()).toBeCalledWith(expected)

    Expected mock function to have been called with:
      ["Test"]
    But it was not called.

      73 |     let param = "Hello"
      74 |     myTestFunction(param);
    > 75 |     expect(localStorageMock.setItem).toBeCalledWith("Test");
         |                                      ^

      at Object.toBeCalledWith (src/__tests__/reducers/index.test.js:75:38)

I am not sure what I am doing wrong here. I am creating a mock localStorage. I threw the function into the test and it still throws this failed test of it not being called. Help?

EDIT: The whole point of this test is to see if that localStorage.setItem("Test, param); gets called or not.

1 Answers

The solution I ended up using was: expect(localStorage.getItem("Test")).toBeDefined(); but I am happy to hear if anyone has a more dynamic solution.

Related