简体   繁体   中英

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:

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:

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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