React Jest 单元测试用例:模拟 dispatch 和处理回调

假设我们有以下的 React 组件:

import { useDispatch } from 'react-redux';
import { useState } from 'react';

function ExampleComponent() {
  const [data, setData] = useState(null);
  const dispatch = useDispatch();

  const handleButtonClick = () => {
    dispatch({ type: 'FETCH_DATA' });
  };

  const handleDataReceived = (data) => {
    setData(data);
  };

  useEffect(() => {
    const unsubscribe = subscribeToData(handleDataReceived);

    return () => {
      unsubscribe();
    };
  }, []);

  return (
    <div>
      <button onClick={handleButtonClick}>Fetch Data</button>
      <div>{data}</div>
    </div>
  );
}

我们想要测试 handleButtonClick 函数,模拟 dispatch 并处理回调。我们可以使用 jestreact-testing-library 来完成这个测试用例。

import { render, fireEvent } from '@testing-library/react';
import { useDispatch } from 'react-redux';
import ExampleComponent from './ExampleComponent';

// 模拟 subscribeToData 函数的返回值
const unsubscribe = jest.fn();

jest.mock('react-redux', () => ({
  useDispatch: jest.fn(),
}));

jest.mock('./subscribeToData', () => ({
  subscribeToData: jest.fn(() => unsubscribe),
}));

describe('ExampleComponent', () => {
  beforeEach(() => {
    useDispatch.mockReturnValue(jest.fn());
  });

  afterEach(() => {
    jest.resetAllMocks();
  });

  it('should dispatch FETCH_DATA action when button is clicked', () => {
    const dispatchMock = jest.fn();
    useDispatch.mockReturnValue(dispatchMock);

    const { getByText } = render(<ExampleComponent />);

    fireEvent.click(getByText('Fetch Data'));

    expect(dispatchMock).toHaveBeenCalledWith({ type: 'FETCH_DATA' });
  });

  it('should set data state when data is received', () => {
    const { getByText } = render(<ExampleComponent />);

    // 模拟 subscribeToData 函数的回调
    const handleDataReceived = subscribeToData.mock.calls[0][0];
    handleDataReceived('test data');

    expect(getByText('test data')).toBeInTheDocument();
  });

  it('should unsubscribe from data updates on unmount', () => {
    const { unmount } = render(<ExampleComponent />);

    unmount();

    expect(unsubscribe).toHaveBeenCalled();
  });
});

在第一个测试用例中,我们使用 jest.fn() 创建了一个 dispatchMock 函数,并将其作为 useDispatch 的返回值。我们使用 render 函数呈现了 ExampleComponent,然后模拟了用户点击按钮的行为。最后,我们使用 toHaveBeenCalledWith 断言来检查 dispatchMock 是否被调用,并传递了一个 { type: 'FETCH_DATA' } 的对象作为参数。

在第二个测试用例中,我们测试了 handleDataReceived 函数。我们使用 render 函数呈现了 ExampleComponent,并模拟了 subscribeToData 函数的回调。我们使用 getByText 函数来获取组件中的文本,然后使用 toBeInTheDocument 断言来检查文本是否存在。

在第三个测试用例中,我们测试了组件的卸载。我们使用 render 函数呈现了 ExampleComponent,然后使用 unmount 函数卸载了组件。最后,我们使用 toHaveBeenCalled 断言来检查 unsubscribe 是否被调用。

React Jest 单元测试用例:模拟 dispatch 和处理回调

原文地址: https://www.cveoy.top/t/topic/oiiw 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录