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