[英]How to test correct state update in async componentDidMount axios call?
I have the following lifecycle with async/await
我有
async/await
的以下生命周期
async componentDidMount() {
try {
const { name, key, expiration } = await DataService.getdata();
this.setState({
key,
expiration,
name,
});
} catch (err) {
console.log(err);
}
}
I wrote the following test to test in state updated correctly when data comes from await call: 我编写了以下测试,以便在数据来自等待调用时正确更新状态:
jest.mock("axios");
test('correct state update', () => {
const responseText = {
name: "test name",
key: "test_key",
expiration: null,
};
axios.get.mockResolvedValueOnce(responseText);
const wrapper = shallow(<ComponentWrapper />);
setImmediate(() => {
expect(wrapper.state().name).toBe('test name');
done();
});
});
But I have an error when the test runs: 但测试运行时出错:
throw error;
^
Error: expect(received).toBe(expected) // Object.is equality
Expected: "test name"
Received: undefined
Also, the test never ends, it continues to run 此外,测试永远不会结束,它继续运行
If I remove this test and just run test for correct rendering I have the following error: 如果我删除此测试并只运行测试以获得正确的渲染,则会出现以下错误:
TypeError: Cannot read property 'get' of undefined
at Function.get (DataService.js:10:32)
Here is the solution: 这是解决方案:
index.ts
: index.ts
:
import React, { Component } from 'react';
import { DataService } from './DataService';
interface ISomeComponentState {
name: string;
key: string;
expiration: string | null;
}
export class SomeComponent extends Component<any, ISomeComponentState> {
constructor(props) {
super(props);
this.state = {
name: '',
key: '',
expiration: ''
};
}
public async componentDidMount() {
try {
const { name, key, expiration } = await DataService.getdata();
this.setState({ key, expiration, name });
} catch (err) {
console.log(err);
}
}
public render() {
const { name, key, expiration } = this.state;
return (
<div>
key: {key}, name: {name}, expiration: {expiration}
</div>
);
}
}
DataService.ts
: DataService.ts
:
import axios from 'axios';
class DataService {
public static async getdata() {
return axios.get(`https://github.com/mrdulin`).then(() => {
return {
name: 'real name',
key: 'real key',
expiration: null
};
});
}
}
export { DataService };
Unit test: 单元测试:
import React from 'react';
import { shallow } from 'enzyme';
import { SomeComponent } from './';
import { DataService } from './DataService';
jest.mock('./DataService.ts');
DataService.getdata = jest.fn();
describe('SomeComponent', () => {
const responseText = {
name: 'test name',
key: 'test_key',
expiration: null
};
it('correct state update', done => {
(DataService.getdata as jest.MockedFunction<typeof DataService.getdata>).mockResolvedValueOnce(responseText);
const wrapper = shallow(<SomeComponent></SomeComponent>);
setImmediate(() => {
expect(wrapper.state('name')).toBe(responseText.name);
done();
});
});
});
Unit test result with coverage report: 覆盖率报告的单元测试结果:
PASS src/stackoverflow/56281185/index.spec.tsx (5.697s)
SomeComponent
✓ correct state update (24ms)
----------------|----------|----------|----------|----------|-------------------|
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s |
----------------|----------|----------|----------|----------|-------------------|
All files | 88.46 | 100 | 71.43 | 85 | |
DataService.ts | 71.43 | 100 | 33.33 | 71.43 | 5,6 |
index.tsx | 94.74 | 100 | 100 | 92.31 | 25 |
----------------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 6.582s
Here is the completed demo: https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/56281185 这是完成的演示: https : //github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/56281185
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.