我在测试componentDidMount()
内的承诺失败时会发生什么问题。以下是相关代码:
//TEST FILE
it('should show an error message when ZipkinService is down', async () => {
const getTraces = ZipkinService.getTraces.mockImplementation(() => Promise.reject('FAIL'));
const getTraceById = ZipkinService.getTraceById.mockImplementation(() => Promise.reject('FAIL'));
const tree = Enzyme.mount(
<TraceListComponent value={''} />
);
await tree.instance().componentDidMount();
console.log(tree.debug());
expect(tree.state().error).toBe('FAIL');
});
//REACT COMPONENT
componentDidMount() {
return this.refreshData(this.props.value);
}
public refreshData(value: string) {
let self = this;
if (value !== '') {
return ZipkinService.getTraceById(value).then(function(trace) {
self.setState({traceList: [trace], error: undefined});
}).catch(function(errorMessage) {
self.setState({traceList: [], error: errorMessage});
});
}
else {
return ZipkinService.getTraces().then(function(traces) {
self.setState({traceList: traces, error: undefined});
}).catch(function(errorMessage) {
console.log("CATCH HERE");
self.setState({traceList: [], error: errorMessage});
});
}
}
但是测试总是失败并不重要,我无法弄清楚原因。我能得到的最接近的是把期望置于process.nextTick()
之内,但这似乎是错误的。我注意到基于打印语句,它是因为测试发生在之前实际更新错误。因此,每次测试运行时,它都会在更新之前获得undefined
。