question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Unable to mock axios instances

See original GitHub issue

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.

Issue Analytics

  • State:closed
  • Created 5 years ago
  • Reactions:4
  • Comments:8

github_iconTop GitHub Comments

35reactions
lifaytcommented, 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!

2reactions
single-stop-justincommented, Aug 11, 2020

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())

Read more comments on GitHub >

github_iconTop Results From Across the Web

Can't mock axios instance in Typescript - Stack Overflow
Something to do with Typescript import/export. I think you should mock default export. So instead of jest.mock('../.
Read more >
axios-response-mock - npm
A library to be used with axios to selectively provide mock responses for any requests that are to be sent via the axios...
Read more >
Mocking axios in Jest tests with Typescript - C.S. Rhymes
Recently I wanted to write a test for a React component that uses axios to retrieve information from an API. To do this...
Read more >
axios error 404 - You.com | The AI Search Engine You Control
Axios catch error Request failed with status code 404 ... If axios instance adapter (xhr or http) taked over by axios-mock-adapter, there will...
Read more >
Axios Mocking with React - Bits and Pieces
1. Setting up Axios Mock Adapter. When it comes to mocking Axios, it all starts with the Mock Adapter. · 2. Using the...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found