mock custom instance of axios in vue jest test

﹥>﹥吖頭↗ 提交于 2020-04-17 21:31:43

问题


The Problem

I have a custom axios instance at src/axios:

import axios from 'axios';

 const instance = axios.create({
   baseURL: 'myApi/',
 });

export default instance;

In MyComponent I import axios with import axios from '../axios' and make an api call.

In testing the api call in MyComponent I must mock axios so I do:

import axios from 'axios'; jest.mock('axios');

but when I run my test axios is undefined inside MyComponent and the test fails.

What I Tried

  1. importing the custom axios instance into the test gives the same error, axios is undefined.
  2. in MyComponent I import axios from node_modules eg import axios from 'axios' then the test works but I can't use my custom axios instance.

Vue 2.6, Jest @vue/cli-plugin-unit-jest 4.2.3

How can I use the custom instance in MyComponent and mock it in the test?

来源:https://stackoverflow.com/questions/60745903/mock-custom-instance-of-axios-in-vue-jest-test

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!