[英]How to TEST async calls made in componentDidMount that set the state of React Component
[英]How to test correct state update in async componentDidMount axios call?
我有async/await
的以下生命周期
async componentDidMount() {
try {
const { name, key, expiration } = await DataService.getdata();
this.setState({
key,
expiration,
name,
});
} catch (err) {
console.log(err);
}
}
我編寫了以下測試,以便在數據來自等待調用時正確更新狀態:
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();
});
});
但測試運行時出錯:
throw error;
^
Error: expect(received).toBe(expected) // Object.is equality
Expected: "test name"
Received: undefined
此外,測試永遠不會結束,它繼續運行
如果我刪除此測試並只運行測試以獲得正確的渲染,則會出現以下錯誤:
TypeError: Cannot read property 'get' of undefined
at Function.get (DataService.js:10:32)
這是解決方案:
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
:
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 };
單元測試:
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();
});
});
});
覆蓋率報告的單元測試結果:
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
這是完成的演示: https : //github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/56281185
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.