简体   繁体   English

如何用 mocking 测试 axios 本身?

[英]How can I test axios itself with mocking it?

I've just started learning react unit testing and the whole mock thing is confusing for me and I couldn't understand it.我刚刚开始学习反应单元测试,整个模拟的东西让我感到困惑,我无法理解。

I'm using axios to fetch data and display it in app component here:我正在使用 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>
    );

And I test the whole loading and name thing in app.test.js:我在 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();
    });
});

And all these tests pass successfully.所有这些测试都成功通过。

What I want to achieve is how can I test the axios itself by mocking it in app.test.js the easiest way?我想要实现的是如何通过 mocking 在 app.test.js 中以最简单的方式测试 axios 本身?

You can try out both scenarios for your request, where it fails and succeeds and have some assertions accordingly.您可以针对您的请求尝试两种方案,其中它失败和成功并相应地有一些断言。 as far as testing workflows involving axios, this answer describes it very well withut using any extra library: stackoverflow.com/a/51654713/7040146至于涉及 axios 的测试工作流程,这个答案很好地描述了它,而不使用任何额外的库:stackoverflow.com/a/51654713/7040146

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM