-1

Using jest and react-testing-libary.

I have data in my server, to get this data I need to log in, and then fetch it. Is there a way to make this data available across all test files?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Omer Dital
  • 73
  • 4

2 Answers2

0

The way I usually do it is by using the beforeAll hook in the setupTests.js file. This way the code inside beforeAll hook will run before each test file is run and i will get fresh data each time.

get data in beforeAll async --> run test-file 1
get data in beforeAll async --> run test-file 2
...
...

I usually also cleanup everything with afterAll hook just to make sure my data is not getting mixed up in between test files being executed.

Sample code like so:

// setupTests.js file

beforeAll(async () => {
  const response = await fetch("url-to-my-server");
  const data = await response.json();

  // store the data as a global variable by using global object
  global.sampleData = data;
});

// cleanup any data or resources below:
afterAll(()=> global.sampleData='');

then inside my test files, I can use that data like this:

test("renders soemthing", () => {
  const data = global.sampleData;
  expect(data).toBe({whatever-i-expect-it-to-be});
});

More info in docs here

nishkaush
  • 1,512
  • 1
  • 13
  • 20
0

You should mock the front-end code that fetches data from your server, using Jest mock utilities. This allows you to control the server data in your test, so it is always the same, and to spy on HTTP calls made by your components.

If you have functions that send HTTP requests, you can mock these functions very easily and make them return values you need :

// in module.js:
// export const getData = () => { ... return Promise from HTTP call }
import * as MyHttpModule from 'module'

// in Jest test
const getDataMock = jest.spyOn(MyHttpModule, 'getData').mockResolvedValue(['mocked', 'data']);

This is just one way to do it, regarding your setup it might be different.

If you are using create-react-app you can add this code in setupTests.js so it will be executed before all tests.

You should never have real HTTP calls in your unit tests, it is also worth noting that Jest runs in a Node environment where fetch API is not available.

Jest Fetch Mock could also help you on this topic.

Florian Motteau
  • 3,467
  • 1
  • 22
  • 42