我正在嘗試使用 jest 和 react 測驗庫撰寫單元測驗。我想測驗 useEffect 鉤子內的函式呼叫,但我的測驗不起作用。我需要做什么才能成功通過測驗?
useEffect(() => {
getActiveFilters(filterValue);
// eslint-disable-next-line
}, [filterValue, dictionaries]);
這是我的測驗
it('should call the [getActiveFilters] function', async () => {
const getActiveFilters = jest.fn();
await waitFor(() => expect(getActiveFilters).toHaveBeenCalled());
});

uj5u.com熱心網友回復:
我知道很難在組件中模擬功能。您應該對某些模塊使用 spy(test double)。正確檢查檔案中渲染元素的方式也是一個好主意。
這是我的例子。
測驗代碼
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: {}
});
});
零件
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;
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/403753.html
標籤:
