How to test useEffect in react testing library 1

How to test useEffect in react testing library

import { List } from './';
import React from 'react';
import '@testing-library/jest-dom/extend-expect';
import { render, waitForElement } from '@testing-library/react';

describe('59892259', () => {
  let originFetch;
  beforeEach(() => {
    originFetch = (global as any).fetch;
  });
  afterEach(() => {
    (global as any).fetch = originFetch;
  });
  it('should pass', async () => {
    const fakeResponse = { title: 'example text' };
    const mRes = { json: jest.fn().mockResolvedValueOnce(fakeResponse) };
    const mockedFetch = jest.fn().mockResolvedValueOnce(mRes as any);
    (global as any).fetch = mockedFetch;
    const { getByTestId } = render();
    const div = await waitForElement(() => getByTestId('test'));
    expect(div).toHaveTextContent('example text');
    expect(mockedFetch).toBeCalledTimes(1);
    expect(mRes.json).toBeCalledTimes(1);
  });
});

Here is what the above code is Doing:
1. We’re mocking the fetch function with a jest.fn()
2. We’re mocking the response of the fetch function with a mockResolvedValueOnce()
3. We’re mocking the json() function of the response with a mockResolvedValueOnce()
4. We’re asserting that the fetch function is called once
5. We’re asserting that the json() function of the response is called once
6. We’re asserting that the div element has the text ‘example text’

Similar Posts