2

I'm new to Jest (and testing javascript in general). I've got a Register component which is basically a page to register a user. When the form is completed and the submit button is clicked it will use axios to send a POST request to the server.

I'm trying to write the test for this functionality. To do so I need to mock axios. I wrote the following test but when asserting that axios was called I'm getting an error:

 expect(jest.fn()).toHaveBeenCalled()

Expected number of calls: >= 1
Received number of calls:    0

Here's my test:

jest.mock('axios')

it('should save value when submitted', async () => {

            render(
                <Register />
            );

            ReactTestUtils.Simulate.change(field('email'), {
                target: { value: 'test@mail.com', name: 'email'}
            })

            ReactTestUtils.Simulate.change(field('first-name'), {
                target: { value: 'test', name: 'first-name'}
            })

            ReactTestUtils.Simulate.change(field('last-name'), {
                target: { value: 'test', name: 'last-name'}
            })

            ReactTestUtils.Simulate.change(field('password'), {
                target: { value: 'test', name: 'password'}
            })

            ReactTestUtils.Simulate.change(field('confirm-password'), {
                target: { value: 'test', name: 'confirm-password'}
            })


            const postSpy = jest.spyOn(axios, 'post')

            ReactTestUtils.Simulate.submit(form('register'));

            expect(postSpy).toHaveBeenCalled();

        });

Basically I'm populating all the required fields from my form and then submitting it.

The function that handles submission in my Register component looks like this:

const onSubmit = data => {
        const res = axios.post("http://localhost/register", data);
    }

Any idea what am I missing or doing wrong?

Thanks

MrCujo
  • 1,218
  • 3
  • 31
  • 56
  • Where do the `field()` and `form()` functions come from? – Phil Jul 19 '21 at 01:50
  • Those are just helpers I’ve defined to get the form and a field in the form respectively. They work fine, I have other tests that use them – MrCujo Jul 19 '21 at 01:55
  • Your code does not call `axios.post()`, it calls `axios()` so your `axios.post` spy will never be called – Phil Jul 19 '21 at 01:56
  • Ohh yes, I see it. I’m calling axios and defining the method in the passed object, I’m not calling axios.post. Will replace my code and try it out again. Thanks very much – MrCujo Jul 19 '21 at 02:15
  • @Phil I updated my code to use `post` (the code for this question was updated as well) yet I'm getting the exact same result – MrCujo Jul 19 '21 at 15:16
  • Have a look at [this answer](https://stackoverflow.com/a/54502525/283366). That always works for me and you might find some hints – Phil Jul 19 '21 at 21:37

0 Answers0