Дми*_*нец 5 reactjs jestjs react-testing-library
我正在尝试使用 jest 和 React 测试库编写单元测试。我想测试 useEffect 挂钩内的函数调用,但我的测试不起作用。我需要做什么才能成功通过测试?
useEffect(() => {
getActiveFilters(filterValue);
// eslint-disable-next-line
}, [filterValue, dictionaries]);
Run Code Online (Sandbox Code Playgroud)
这是我的测试
it('should call the [getActiveFilters] function', async () => {
const getActiveFilters = jest.fn();
await waitFor(() => expect(getActiveFilters).toHaveBeenCalled());
});
Run Code Online (Sandbox Code Playgroud)
我知道在组件中模拟函数很困难。您应该对某些模块使用间谍(测试双)。正确检查文档中渲染元素的方法也是个好主意。
这是我的例子。
it('axios spy and rendering test', async () => {
const spyAxios = jest.spyOn(axios, 'get').mockResolvedValue({
data: 'Junhyunny'
});
render(<SecondAuth />);
await waitFor(() => {
expect(screen.getByText('Sir Junhyunny')).toBeInTheDocument();
});
expect(spyAxios).toHaveBeenNthCalledWith(1, 'http://localhost:8080', {
params: {}
});
});
Run Code Online (Sandbox Code Playgroud)
import {useEffect, useState} from "react";
import axios from "axios";
const SecondAuth = () => {
const [name, setName] = useState('');
useEffect(() => {
axios.get('http://localhost:8080', {
params: {}
}).then(({data}) => {
setName(data);
});
}, []);
return (
<div>
<p>Sir {name}</p>
</div>
);
};
export default SecondAuth;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9084 次 |
| 最近记录: |