ctimmerm / axios-mock-adapter

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

Allow mock overrides #271

Closed callumbooth closed 4 years ago

callumbooth commented 4 years ago

Sorry if there is a way to do this already but in jest mocks its possible to override existing mocks with a new one. Such as jest.fn().mockReturnValue(someVal) and then within a test do jest.fn().mockReturnValueOnce(otherVal) to override the value once.

However it seems that this isn't possible with axios-mock-adapter. Take the following code. This wont work as the initial .reply() will be used as the response not the latest .networkErrorOnce()

///some imports

const mock = new MockAdapter(axios)
mock.onGet('some/route').reply(200, someData)

describe('test suite', () => {
  it('should return someData', () => {
    const res = myFunc() // calls axios.get('some/route')
    expect(res).toBe(someData) //this will pass
  })

  it('should return someData', () => {
    mock.onGet('some/route').networkErrorOnce()
    const res = myFunc() // calls axios.get('some/route')
    expect(res).toThrowError() //this will fail, and no network error will have occurred.
  })

  it('should return someData', () => {
    const res = my2ndFunc() // calls axios.get('some/route')
    expect(res).toBe(someData) //this will pass
  })
})

Digging into the code I think its because of this function looping through items forward but if we loop backwards this would work. For e.g.

//...other utils

function findReverse(array, predicate) {
  var length = array.length;
  for (var i = length - 1; i > 0; i--) {
    var value = array[i];
    if (predicate(value)) return value;
  }
}

function findHandler(handlers, method, url, body, parameters, headers, baseURL) {
  return findReverse(handlers[method.toLowerCase()], function(handler) {
    // ...rest of the function
  })
}

//...more utils

I'm happy to create a PR but wanted to check if there is already a solution for what I'm trying to do and if what I have found is indeed a bug.

ctimmerm commented 4 years ago

I think this is the same as described in https://github.com/ctimmerm/axios-mock-adapter/issues/257. The current behavior is intentional, but I'm open to a PR that adds this functionality alongside the current.