已关注 this link ,我尝试在模拟 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();
});
});
当我运行此测试时,我收到以下失败消息:
● MainContainer › encountered a declaration exception
TypeError: Cannot read property 'get' of undefined
14 |
15 | public componentDidMount() {
> 16 | axios_firebase.get('url_to_data')
我以为我完全遵循了最初的链接..我无法想象使用 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))
}
};
});
参见https://github.com/kulshekhar/ts-jest/issues/120#issuecomment-283653644 .
关于reactjs - 无法在 Typescript 中模拟 axios 实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52774386/