0

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 ?

Mehdi Faraji
  • 2,574
  • 8
  • 28
  • 76
  • 1
    Unless you're writing code for the axios project, you should *not* be testing axios itself; rather, trust that it's been tested, and stub/mock its functions, so you test your code and its interaction with axios. How to do that is something I can't say as I use a different testing framework. – 404 Jun 22 '20 at 15:04
  • @404 So could you please tell me If this testing code is enough for a react project which is using axios in some part of it ? – Mehdi Faraji Jun 22 '20 at 15:33
  • 1
    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: https://stackoverflow.com/a/51654713/7040146 – Varun Sharma Jun 25 '20 at 11:44

1 Answers1

0

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

Mehdi Faraji
  • 2,574
  • 8
  • 28
  • 76