【发布时间】:2018-01-07 21:07:26
【问题描述】:
我有一个基本组件,它在 componentDidMount 阶段调用 web 服务并覆盖我状态下的 contents 值:
import React, {Component} from 'react';
import {Text} from "react-native";
class Widget extends Component {
constructor() {
super();
this.state = {
contents: 'Loading...'
}
}
async componentDidMount() {
this.setState(...this.state, {
contents: await this.getSomeContent()
});
}
render() {
return (
<Text>{this.state.contents}</Text>
)
}
async getSomeContent() {
try {
return await (await fetch("http://someurl.com")).text()
} catch (error) {
return "There was an error";
}
}
}
export default Widget;
我想使用 Jest 快照在以下每种情况下捕获我的组件的状态:
- 加载中
- 成功
- 错误
问题是我必须引入片状暂停来验证组件的状态。
例如,要查看成功状态,必须在渲染组件后稍作停顿,让 setState 方法有机会赶上:
test('loading state', async () => {
fetchMock.get('*', 'Some Content');
let widget = renderer.create(<Widget />);
// --- Pause Here ---
await new Promise(resolve => setTimeout(resolve, 100));
expect(widget.toJSON()).toMatchSnapshot();
});
我正在寻找克服测试用例中异步性的最佳方法,以便正确验证每个状态的快照。
【问题讨论】:
标签: react-native jestjs