问题是提取是异步进行的。你打电话的时候
wrapper.debug()
状态无法更新,因为
fetch
已将响应放入事件堆栈。所以
取来
已被呼叫
,但它没有返回任何响应。
您可以通过将测试更新为以下内容来看到这一点:
// mock out fetch...
const wrapper = mount(<App />);
expect(fetch).toBeCalled();
setTimeout(() => {
wrapper.update();
console.log(wrapper.debug()); // should be showing the Data component now
}, 0);
这样就可以调用承诺回调
之前
尝试通过将更新/调试代码放在事件堆栈的末尾来查看呈现的标记。
你可以把它包起来
setTimeout
在一个承诺中
it
回调函数,并放置
expects
在你面前
resolve
(否则它可能永远不会运行
expect
测试结束前的功能)。
// mock out fetch...
const wrapper = mount(<App />);
expect(fetch).toBeCalled();
return new Promise((resolve) => {
setTimeout(() => {
wrapper.update();
console.log(wrapper.debug()); // should be showing the Data component now
expect(...)
resolve();
}, 0);
});
另一种方法是测试当状态具有特定数据时,数据的结果是否呈现您所期望的结果:
it("should render the app component once data is there", () => {
const wrapper = shallow(<App />);
wrapper.setState({
loading: false,
data: {
userName: "John",
surName: "Doe"
}
});
console.log(wrapper.debug()); // You'll see the DataComponent
});