How to test useEffect in react testing library

Hello readers! In this article I have shared the details about “How to test useEffect in react testing library”. Okay, let’s move on to the tutorial.

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(<List></List>);
    const div = await waitForElement(() => getByTestId('test'));
    expect(div).toHaveTextContent('example text');
    expect(mockedFetch).toBeCalledTimes(1);
    expect(mRes.json).toBeCalledTimes(1);
  );
);

Final Words

I hope this post helps you to know about “How to test useEffect in react testing library”. If you have any questions regarding this tutorial please let us know via the comment section. Share this tutorial with your friends and family via social networks.

Hi, I'm Ranjith a full-time Blogger, YouTuber, Affiliate Marketer, & founder of Coder Diksha. Here, I post about programming to help developers.

Share on:

Leave a Comment