Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Unable to mock axios instances #166

Closed
ingro opened this issue Sep 27, 2018 · 8 comments
Closed

Unable to mock axios instances #166

ingro opened this issue Sep 27, 2018 · 8 comments

Comments

@ingro
Copy link

ingro commented Sep 27, 2018

Hello 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.

@BlueAccords
Copy link

hey @ingro did you ever figure out a better way to handle this use case? I'm trying to test instances of axios too as I wanted to have global interceptors to handle the errors.

@lifayt
Copy link

lifayt commented Oct 10, 2018

Hey,

I thought I was running into a similar problem, but the following code works for me:

// httpServices.js
export const api = axios.create()

and

// httpServices.test.js
import {
  api
} from './httpServices'

describe('httpServices tests', () => {
    beforeAll(() => {
        mock = new MockAdapter(api)
   })
})

Hope that helps!

@BlueAccords
Copy link

Thanks! and yeah I found out it was working for me too but I was calling it with the wrong URL formatting in the mock/test.

@lifayt
Copy link

lifayt commented Oct 10, 2018

I ran into this issue because of global interceptors as well :)

@mwmcode
Copy link

mwmcode commented May 27, 2019

how do you test it you're calling the client constructor directly:

const config = {
method: 'GET',
url: 'some/url/here',
};
await client(config));

expect(mock.instance.get).toHaveBeenCalledTimes(1); doesn't work

@single-stop-justin
Copy link

I am having this issue as well. I can mock axios if I am calling axios.get directly in my test, but if I call another function with axios in it, that function's axios.get doesn't use the mocked axios.get

Test:

import axios from 'axios'

jest.mock('axios')

describe('My Tests', () => {
  describe('The Test', () => {
    it('Returns generic error for network errors', async () => {
      axios.get.mockImplementation(() => Promise.reject())

      await expect(myFunction(input)).rejects.toBeUndefined()

myFunction(input)

import axios from 'axios'

export const myFunction= (input) =>
  new Promise((resolve, reject) => {
    axios
      .get(url)
      .then((result) => {
        if(result.true) resolve()
        if(result.false) reject()
      })
      .catch((error) => reject())
  })

Expected: axios uses axios.get.mockImplementation(() => Promise.reject())
Actual: axios hits the API and does not call the mock implementation

Same thing happens with axios.get.mockImplementationOnce(() => Promise.reject())

@MilanCtd
Copy link

@single-stop-justin did you solve your problem? I am running into the same issue :(

@noam7700
Copy link

noam7700 commented Oct 2, 2022

What if I want to mock all instances in my test file?

Seems really annoying to extract all instances, and mock accordingly their requests

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

8 participants