ctimmerm / axios-mock-adapter

Axios adapter that allows to easily mock requests
MIT License
3.47k stars 245 forks source link

Mock doest not record api call after calling resetHistory() #361

Closed nguyenhoanglam closed 3 months ago

nguyenhoanglam commented 1 year ago

Here is my test code

it('should call update api', async () => {
    axios.resetHistory();
    axios.onPost('api/update').reply(200, {});

    // userService.update() should call axios.post('api/update')
    await userService.update({name: "Test"});
    expect(axios.history.post.length).toBe(1);
  });

I expect post.length should be 1 but received 0. It looks like the mock doest not record any api call after calling resetHistory. Any help please?

Techie-Ali commented 3 months ago

Agreed +1 to fix this

marcbachmann commented 3 months ago

This works as intended 🤔

import axios from 'axios'
import MockAdapter from 'axios-mock-adapter'

const mock = new MockAdapter(axios)
mock.onPost('/something').reply(200, {foo: 'bar'})
mock.onPost('/somethingelse').reply(200, {foo: 'bar'})

await axios.post('/something')
console.log('first request', mock.history.post[0].url)

mock.resetHistory()
await axios.post('/somethingelse')
console.log('second request', mock.history.post[0].url)

output:

first request /something
second request /somethingelse

Remember to always reference the same axios instance you're using. If you mock the main instance, it won't intercept child instances create using axios.create()