模拟内部axios.create()

kyw*_*kyw 5 javascript reactjs jestjs axios create-react-app

我正在使用jestaxios-mock-adapter测试异步动作创建器中的axiosAPI调用redux.

当我使用axios这样创建的实例时,我无法使它们工作axios.create():

import axios from 'axios';

const { REACT_APP_BASE_URL } = process.env;

export const ajax = axios.create({
  baseURL: REACT_APP_BASE_URL,
});
Run Code Online (Sandbox Code Playgroud)

我会用它来消费它async action creator:

import { ajax } from '../../api/Ajax'

export function reportGet(data) {
  return async (dispatch, getState) => {
    dispatch({ type: REQUEST_TRANSACTION_DATA })

    try {
      const result = await ajax.post(
         END_POINT_MERCHANT_TRANSACTIONS_GET,
         data,
      )
      dispatch({ type: RECEIVE_TRANSACTION_DATA, data: result.data })
      return result.data
    } catch (e) {
      throw new Error(e);
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

这是我的测试文件:

import {
  reportGet,
  REQUEST_TRANSACTION_DATA,
  RECEIVE_TRANSACTION_DATA,
} from '../redux/TransactionRedux'
import configureMockStore from 'redux-mock-store'
import thunk from 'redux-thunk'
import { END_POINT_MERCHANT_TRANSACTIONS_GET } from 'src/utils/apiHandler'
import axios from 'axios'
import MockAdapter from 'axios-mock-adapter'

const middlewares = [thunk]
const mockStore = configureMockStore(middlewares)
const store = mockStore({ transactions: {} })

test('get report data', async () => {
  let mock = new MockAdapter(axios)

  const mockData = {
    totalSalesAmount: 0
  }

  mock.onPost(END_POINT_MERCHANT_TRANSACTIONS_GET).reply(200, mockData)

  const expectedActions = [
    { type: REQUEST_TRANSACTION_DATA },
    { type: RECEIVE_TRANSACTION_DATA, data: mockData },
  ]

  await store.dispatch(reportGet())
  expect(store.getActions()).toEqual(expectedActions)
})
Run Code Online (Sandbox Code Playgroud)

我只得到一个动作,Received: [{"type": "REQUEST_TRANSACTION_DATA"}]因为有一个错误ajax.post.

我已经尝试了很多方法来嘲笑axios.create无效而不知道我在做什么......非常感谢.

kyw*_*kyw 18

好,我知道了.这是我修复它的方法!我最终没有任何模拟库axios!

axiosin 创建一个模拟src/__mocks__:

// src/__mocks__/axios.ts

const mockAxios = jest.genMockFromModule('axios')

// this is the key to fix the axios.create() undefined error!
mockAxios.create = jest.fn(() => mockAxios)

export default mockAxios
Run Code Online (Sandbox Code Playgroud)

然后在你的测试文件中,要点看起来像:

import mockAxios from 'axios'
import configureMockStore from 'redux-mock-store'
import thunk from 'redux-thunk'

// for some reason i need this to fix reducer keys undefined errors..
jest.mock('../../store/rootStore.ts')

// you need the 'async'!
test('Retrieve transaction data based on a date range', async () => {
  const middlewares = [thunk]
  const mockStore = configureMockStore(middlewares)
  const store = mockStore()

  const mockData = {
    'data': 123
  }

  /** 
   *  SETUP
   *  This is where you override the 'post' method of your mocked axios and return
   *  mocked data in an appropriate data structure-- {data: YOUR_DATA} -- which
   *  mirrors the actual API call, in this case, the 'reportGet'
   */
  mockAxios.post.mockImplementationOnce(() =>
    Promise.resolve({ data: mockData }),
  )

  const expectedActions = [
    { type: REQUEST_TRANSACTION_DATA },
    { type: RECEIVE_TRANSACTION_DATA, data: mockData },
  ]

  // work
  await store.dispatch(reportGet())

  // assertions / expects
  expect(store.getActions()).toEqual(expectedActions)
  expect(mockAxios.post).toHaveBeenCalledTimes(1)
})
Run Code Online (Sandbox Code Playgroud)

  • 谢谢!这很有帮助。我必须添加`<typeof axios>`,否则`mockAxios`被标记为`未知类型`:` const mockAxios = jest.genMockFromModule<typeof axios>('axios'); mockAxios.create = jest.fn(() => mockAxios); ` (10认同)
  • @ReinierKaper 非常确定返回值隐含在该箭头函数模式中:) (2认同)
  • 建议在node_modules同一级别创建\_\_mocks\_\_目录,更多定义[此处](https://jestjs.io/docs/en/manual-mocks#mocking-node-modules) (2认同)

Sas*_*asa 16

如果您需要创建在特定测试中模拟with的Jest测试(并且不需要所有测试用例都模拟 axios,如其他答案中所述),您还可以使用:axioscreate

const axios = require("axios");

jest.mock("axios");

beforeAll(() => {
    axios.create.mockReturnThis();
});

test('should fetch users', () => {
    const users = [{name: 'Bob'}];
    const resp = {data: users};
    axios.get.mockResolvedValue(resp);

    // or you could use the following depending on your use case:
    // axios.get.mockImplementation(() => Promise.resolve(resp))

    return Users.all().then(data => expect(data).toEqual(users));
});
Run Code Online (Sandbox Code Playgroud)

这是在 Jest 中 Axios 模拟的相同示例的链接,无需create. 区别在于添加axios.create.mockReturnThis()

  • @mikemaccana 如果您与 Typescript 一起使用,则需要提供 `axios as jest.Mocked<typeof axios>` (5认同)
  • 只要您在模拟运行之前不调用 axios.create ,就可以完美工作。很好谢谢。@mikemaccana 我会确保你在这种情况下正确地嘲笑 axios,如第二行所示 (3认同)
  • 尝试这个,我得到`TypeError: axios.create.mockReturnThis is not a function` (2认同)

小智 8

这是我对 axios 的模拟

export default {
    defaults:{
        headers:{
            common:{
                "Content-Type":"",
                "Authorization":""
            }
        }
  },
  get: jest.fn(() => Promise.resolve({ data: {} })),
  post: jest.fn(() => Promise.resolve({ data: {} })),
  put: jest.fn(() => Promise.resolve({ data: {} })),
  delete: jest.fn(() => Promise.resolve({ data: {} })),
  create: jest.fn(function () {
      return {
          interceptors:{
              request : {  
                  use: jest.fn(() => Promise.resolve({ data: {} })),
              }
          },

          defaults:{
                headers:{
                    common:{
                        "Content-Type":"",
                        "Authorization":""
                    }
                }
          },
          get: jest.fn(() => Promise.resolve({ data: {} })),
          post: jest.fn(() => Promise.resolve({ data: {} })),
          put: jest.fn(() => Promise.resolve({ data: {} })),
          delete: jest.fn(() => Promise.resolve({ data: {} })),
      }
  }),
};
Run Code Online (Sandbox Code Playgroud)