-1

I have an API call function that retrieves data from my back end to display. My API call as a header that is required for authorisation when retrieving the data. The session storage is set at login when the application is run.

My main code is this:

AdminTable.js
export const ADMIN_URL = '/admin_management/list/';

export const fetchAdmin = async () => {
  try {
    const response = await axios.post(
      ADMIN_URL,
      {},
      {
        headers: { Authorization: `Bearer ${sessionStorage.getItem('access_token')}` },
      }
    );
    return response.data.results;
  } catch (err) {
    console.log(`Error: ${err.message}`);
  }
};

And my testing code is:

AdminTable.test.js
import { fetchAdmin } from '../pages/AdminTable';
import axios from '../api/axios';

jest.mock('../api/axios', () => ({
  post: jest.fn(),
}));
axios.post.mockResolvedValue({ data: { results: 'Mock Jedi' } });

describe('fetchAdmin', () => {
  afterEach(jest.clearAllMocks);
  it('return correct data', async () => {
    const result = await fetchAdmin();
    expect(result).toMatch('Mock Jedi');
    expect(axios.post).toHaveBeenCalledTimes(1);
  });
});

When i run the test i get this error:

Expected substring: "Mock Jedi"
    Received string:    "sessionStorage is not defined"

    > 19 |     expect(result).toMatch('Mock Jedi');
         |                    ^
      20 |     expect(axios.post).toHaveBeenCalledTimes(1);
      21 |   });
      22 | });

How do i mock jest to insert a token for sessionStorage?

If i remove the headers or set Bearer ${'123123'} in AdminTable.js file the test has no issue.

Mehbenmeh
  • 17
  • 5

1 Answers1

0

I found the solution! The issue is that sessionStorage is only available when running on browser. All that i need to is mock a sessionStorage in my test file. You do this by:

global.sessionStorage = {
  getItem: jest.fn(() => 'test token'),
};
Mehbenmeh
  • 17
  • 5