I am trying to test a delete button in my app. When the app initialises it makes an axios request to the server to get a list of benefits. When the delete button is clicked another request is made. For some reason my test just won't intercept the second axios request.
I tried to stub the initial request but I still get the same problem.
The initial request is
useEffect(() => {
axios.get('/api/v1/benefits')
.then(response => {
setBenefits(response.data)
})
}, [])
The function called when the button is clicked is
const deleteBenefit = benefit => {
const id = benefit.id
axios.delete(`/api/v1/benefits/${id}`)
.then(response => {
setBenefits(benefits.filter(benefit => benefit.id !== id))
warning('Benefit Deleted')
})
.catch(error => {
warning('Benefit could not be deleted. Please try again')
})
}
The test is written as
it('deletes the selected benefit', async () => {
const { getByTestId, debug } = render(<Benefits />)
moxios.wait(() => {
const request = moxios.requests.mostRecent()
request.respondWith({
status: 200,
response: benefits
})
})
const deleteButton = await waitForElement(() => getByTestId('deleteButton1'))
fireEvent.click(deleteButton)
moxios.wait(() => {
const request = moxios.requests.mostRecent()
request.respondWith({
status: 204,
}).then(() => {
expect(document.querySelectorAll('tbody > tr').length).toBe(3)
done()
})
})
})
I expect the second moxios.wait to intercept the delete request. The code itself works and when the button is clicked it does send the delete request to the server via the axios request.
I have also confirmed that the test itself does actually call the function because to test it I made a dummy element and updated it which does update the test.
I'm wondering if it's the way moxios.wait works but I can't find anything to suggest the way I'm doing it would be a problem.