Search code examples
javascriptjestjsjest-mock-axios

How do I use a var as the return value in a mocked Jest function?


I currently have this code...

const context = {};
context.response = {};
jest.mock('axios', () => ({
    defaults: {
        withCredentials: true
    },
    post: () => Promise.resolve(context.response)
}));

When I try to run I get...

babel-plugin-jest-hoist: The module factory of jest.mock() is not allowed to reference any out-of-scope variables.

I want to be able to easily change the response object without resetting and remocking. Is there a good way to do this?


Solution

  • That happens because of jest use babel-plugin-jest-hoist, what it means, all of your mocks hoisted to the top. so you can't access variables inside mocks.

    Because we mocked axios, when we import 'axios' we get the mock version so we can use "mockImplementation" method of jest.fn().

    import axios from 'axios'
    
    jest.mock('axios', () => ({
      defaults: {
        withCredentials: true
      },
      post: jest.fn()
    }))
    
    test('should...', () => {
      // mock post for your case
      axios.post.mockImplementation(() => {
        return true
      })
      expect(axios.post()).toBe(true)
    })