Reactjs Can';t在Typescript中模拟axios实例

Reactjs Can';t在Typescript中模拟axios实例,reactjs,typescript,jestjs,enzyme,Reactjs,Typescript,Jestjs,Enzyme,接下来,我尝试在模拟Axios(使用Typescript)时编写一个单元测试 使用Axios实例设置baseUrl // src/infrastructure/axios-firebase.ts import axios from 'axios'; const axiosThroughFirebase = axios.create({ baseURL: 'firebase_URL' }); export default axiosThroughFirebase; 这是我要测试的组件

接下来,我尝试在模拟Axios(使用Typescript)时编写一个单元测试

使用Axios实例设置
baseUrl

// src/infrastructure/axios-firebase.ts
import axios from 'axios';

const axiosThroughFirebase = axios.create({
    baseURL: 'firebase_URL'
});

export default axiosThroughFirebase;
这是我要测试的组件的简化版本

// src/container/MainContainer/MainContainer.tsx
import axios_firebase from '../../infrastructure/axios-firebase';
...

public componentDidMount() {
    axios_firebase.get('firebase_url/data.json')
       .then(resp => this.setState({ stuff }));
}
然后是我的测试文件

// src/container/MainContainer/MainContainer.test.tsx
jest.mock('../../infrastructure/axios-firebase', () => {
    return {
       get: jest.fn(() => Promise.resolve(someFakeData))
    };
});

import axios_firebase from '../../infrastructure/axios-firebase';

test('fetches data on componentDidMount', async () => {
    const wrapper = enzyme.shallow(<MainContainer />);
    wrapper.instance().componentDidMount()
       .then(() => {
           expect(axios_firebase.get).toHaveBeenCalled();
       });
});

我以为我是在跟踪最初的链接。。我无法想象使用Typescript是个问题?我不明白为什么模拟出来的Axios实例在代码中没有定义。

与Typescript导入/导出有关

我认为你应该模拟默认导出。所以不是

jest.mock('../../infrastructure/axios-firebase', () => {
    return {
       get: jest.fn(() => Promise.resolve(someFakeData))
    };
});
应该是

jest.mock('../../infrastructure/axios-firebase', () => {
    return {
       'default' : {
         get: jest.fn(() => Promise.resolve(someFakeData))
       }
    };
});

请参阅。

我使用您的答案解决了这个问题,因此我将它标记为答案。不幸的是,我立即遇到了以下问题。如果您对此也有任何想法,我将非常感谢。因为在componentDidMount()
axios.get(…)中的教程中,然后(…)
返回。是的,我必须亲自面对palm,因为我错过了它。
jest.mock('../../infrastructure/axios-firebase', () => {
    return {
       'default' : {
         get: jest.fn(() => Promise.resolve(someFakeData))
       }
    };
});