使用 react-testing-library 测试 useEffect 内部的 api 调用

IT技术 reactjs typescript unit-testing react-hooks react-testing-library
2021-05-04 13:24:48

我想测试 api 调用和返回的数据,这些数据应该显示在我的功能组件中。我创建了执行 api 调用的 List 组件。我希望返回的数据显示在组件中,为此我使用了 useState 钩子。组件如下所示:

const List: FC<{}> = () => {
    const [data, setData] = useState<number>();
    const getData = (): Promise<any> => {
        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 (
        <div>
            <div id="test">{data}</div>
        </div>
    )
}

我写了一个测试,其中我嘲笑了 fetch 方法。我检查 fetch 方法是否已被调用并且它确实发生了。不幸的是,我不知道如何测试响应返回的值。当我尝试 console.log 时,我只是得到 null,我想得到“示例文本”。我的猜测是我必须等待从 Promise 返回的这个值。不幸的是,尽管尝试使用行为和等待方法,但我不知道如何实现。这是我的测试:

it('test', async () => {
    let component;
    const fakeResponse = 'example text';
    const mockFetch = Promise.resolve({json: () => Promise.resolve(fakeResponse)});
    const mockedFetch = jest.spyOn(window, 'fetch').mockImplementationOnce(() => mockFetch as any )
    await wait( async () => {
        component = render(<List />);
    })
    const value: Element = component.container.querySelector('#test');
    console.log(value.textContent);
    expect(mockedFetch).toHaveBeenCalledTimes(1);
})

我真的很感激任何建议。

第二次尝试

也尝试使用data-testid="test"and waitForElement,但仍然收到空值。

更新的组件增量:

  const List: FC<{}> = () => {
-     const [data, setData] = useState<number>();
+     const [data, setData] = useState<string>('test');
      const getData = (): Promise<any> => {
          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 (
          <div>
-             <div id="test">{data}</div>
+             <div data-testid="test" id="test">{data}</div>
          </div>
      )
  }

和更新的测试:

it('test', async () => {
    const fakeResponse = 'example text';
    const mockFetch = Promise.resolve({json: () => Promise.resolve(fakeResponse)});
    const mockedFetch = jest.spyOn(window, 'fetch').mockImplementationOnce(() => mockFetch as any )
    const { getByTestId } = render(<List />);
    expect(getByTestId("test")).toHaveTextContent("test");
    const resolvedValue = await waitForElement(() => getByTestId('test'));
    expect(resolvedValue).toHaveTextContent("example text");
    expect(mockedFetch).toHaveBeenCalledTimes(1);
})
1个回答

这是一个工作单元测试示例:

index.tsx

import React, { useState, FC } from 'react';

export const List: FC<{}> = () => {
  const [data, setData] = useState<number>();
  const getData = (): Promise<any> => {
    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 (
    <div>
      <div data-testid="test">{data}</div>
    </div>
  );
};

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

单元测试结果:

 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