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并处理回调。我们可以使用jest和react-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是否被调用
原文地址: https://www.cveoy.top/t/topic/fvkf 著作权归作者所有。请勿转载和采集!