【发布时间】:2018-10-12 07:23:56
【问题描述】:
在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 实例在代码中是未定义的。
【问题讨论】:
标签: reactjs typescript jestjs enzyme