Testing api call inside useEffect using react-testing-library

后端 未结 1 1867
终归单人心
终归单人心 2021-02-13 23:22

I want to test api call and data returned which should be displayed inside my functional component. I created List component which performs api call. I would like the returned d

1条回答
  •  孤独总比滥情好
    2021-02-13 23:47

    Here is a working unit testing example:

    index.tsx:

    import React, { useState, FC } from 'react';
    
    export const List: FC<{}> = () => {
      const [data, setData] = useState();
      const getData = (): Promise => {
        return fetch('https://jsonplaceholder.typicode.com/todos/1');
      };
    
      React.useEffect(() => {
        const func = async () => {
          const data = await getData();
          const value = await data.json();
          setData(value.title);
        };
        func();
      }, []);
    
      return (
        
    {data}
    ); };

    index.test.tsx:

    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);
      });
    });
    

    unit test result:

     PASS  src/stackoverflow/59892259/index.test.tsx (9.816s)
      59892259
        ✓ should pass (63ms)
    
    -----------|----------|----------|----------|----------|-------------------|
    File       |  % Stmts | % Branch |  % Funcs |  % Lines | Uncovered Line #s |
    -----------|----------|----------|----------|----------|-------------------|
    All files  |      100 |      100 |      100 |      100 |                   |
     index.tsx |      100 |      100 |      100 |      100 |                   |
    -----------|----------|----------|----------|----------|-------------------|
    Test Suites: 1 passed, 1 total
    Tests:       1 passed, 1 total
    Snapshots:   0 total
    Time:        11.73s, estimated 13s
    

    0 讨论(0)
提交回复
热议问题