我正在尝试为axios请求编写一个Jest测试。 axios请求位于componentDidMount生命周期方法内部,我不知道如何获取它。
反应:
class MyComponent extends Component {
componentDidMount(){
axios
.get('https://jsonplaceholder.typicode.com/users')
.then(res => res.data)
.catch(err => 'catch error')
}
render() {
return (null);
}
}
export default MyComponent;
测试:
import MyComponent from './components/MyComponent';
test('Axios is working', () => {
return MyComponent.prototype.componentDidMount().then(data => {
expect(data).toBeDefined;
});
});
在测试时出现错误:TypeError:无法读取未定义的属性'then'。
所以
MyComponent.prototype.componentDidMount()
不起作用。
所以我的最后一个问题是-如何定义componentDidMount 来测试其中的axios请求?
非常感谢您的回答。
答案 0 :(得分:0)
这是一个解决方案:
index.tsx
:
import { Component } from 'react';
import axios from 'axios';
class MyComponent extends Component {
public async componentDidMount() {
axios
.get('https://jsonplaceholder.typicode.com/users')
.then(res => res.data)
.catch(err => 'catch error');
}
public render() {
return null;
}
}
export default MyComponent;
单元测试:
import MyComponent from './';
import axios from 'axios';
jest.mock('axios');
axios.get = jest.fn();
describe('MyComponent', () => {
describe('test with jestjs', () => {
it('componentDidMount - 1', async () => {
(axios.get as jest.MockedFunction<typeof axios.get>).mockResolvedValueOnce({ data: 'mocked data' });
await MyComponent.prototype.componentDidMount();
expect(axios.get).toBeCalledWith('https://jsonplaceholder.typicode.com/users');
});
it('componentDidMount - 2', async () => {
(axios.get as jest.MockedFunction<typeof axios.get>).mockRejectedValueOnce(new Error('some error'));
const actualValue = await MyComponent.prototype.componentDidMount();
expect(axios.get).toBeCalledWith('https://jsonplaceholder.typicode.com/users');
});
it('render', () => {
expect(MyComponent.prototype.render()).toEqual(null);
});
});
});
覆盖率100%的单元测试结果:
PASS src/stackoverflow/54794512/index.spec.tsx
MyComponent
test with jestjs
✓ componentDidMount - 1 (6ms)
✓ componentDidMount - 2 (1ms)
✓ render (1ms)
-----------|----------|----------|----------|----------|-------------------|
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s |
-----------|----------|----------|----------|----------|-------------------|
All files | 100 | 100 | 100 | 100 | |
index.tsx | 100 | 100 | 100 | 100 | |
-----------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests: 3 passed, 3 total
Snapshots: 0 total
Time: 4.073s
以下是完整的演示:https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/54794512