Unable to mock axios instances
See original GitHub issueHello and thanks for this library!
I have however a problem when trying to test requests made by instances created with axios.create().
I have this client file that I can import in my application where needed with some default settings for the instance (I actually have many of them since I’m using various API in my application):
// client.js
import axios from 'axios';
const client = axios.create({
baseURL: process.env.REACT_APP_API_ROOT,
responseType: 'json'
});
export default client;
// somecomponent.js
import client from './client.js';
class SomeComponent extends React.Component {
componentDidMount() {
client.get('/foo/bar')
.then(res => ...);
}
}
When I try to test the component the call to the api is not intercepted by the mock and the real API is hit, causing errors in the test.
But if I export axios instead of client from client.js the tests run just fine.
So my guessing is that the mock can only be applied to the default instance of axios, and not on subsequently created instances. Is my guess correct? The only workaround I found is to add a condition to the default export in client.js:
export default process.env.NODE_ENV === 'test' ? axios : client;
but that’s not ideal either because I may want to actually hit the API on integration tests.
Are there better ways to handle this problem? Is an improvement that can be implemented on the library in the future? Thanks.
Issue Analytics
- State:
- Created 5 years ago
- Reactions:4
- Comments:8

Top Related StackOverflow Question
Hey,
I thought I was running into a similar problem, but the following code works for me:
and
Hope that helps!
I am having this issue as well. I can mock axios if I am calling
axios.getdirectly in my test, but if I call another function with axios in it, that function’saxios.getdoesn’t use the mockedaxios.getTest:
myFunction(input)
Expected: axios uses
axios.get.mockImplementation(() => Promise.reject())Actual: axios hits the API and does not call the mock implementationSame thing happens with
axios.get.mockImplementationOnce(() => Promise.reject())