[英]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.