[英]What does mocking a function mean in jest. How can I pass the test for below code
[英]How can I test axios itself with mocking it?
我剛剛開始學習反應單元測試,整個模擬的東西讓我感到困惑,我無法理解。
我正在使用 axios 來獲取數據並將其顯示在應用程序組件中:
const [ data, setData ] = React.useState(null);
useEffect(
() => {
const url = '/url';
axios.get(url).then((res) => setData(res.data)).catch((err) => {
console.log('error happened' + err);
});
},
[ data ]
);
return (
<div>
{data ? <p data-testid="name">{data.name}</p> : <p data-testid="loading">Loading...</p>}
</div>
);
我在 app.test.js 中測試了整個加載和命名:
afterEach(cleanup);
describe('App', () => {
test('Render app', async () => {
render(<App />);
expect(screen.getByTestId('loading')).toBeInTheDocument();
const name = await waitForElement(() => screen.getByTestId('name'));
expect(name).toBeInTheDocument();
expect(screen.queryByTestId('loading')).toBeNull();
});
});
所有這些測試都成功通過。
我想要實現的是如何通過 mocking 在 app.test.js 中以最簡單的方式測試 axios 本身?
您可以針對您的請求嘗試兩種方案,其中它失敗和成功並相應地有一些斷言。 至於涉及 axios 的測試工作流程,這個答案很好地描述了它,而不使用任何額外的庫:stackoverflow.com/a/51654713/7040146
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.