gpt4 book ai didi

javascript - 等待 fetch() 解析使用 Jest 进行 React 测试?

转载 作者:行者123 更新时间:2023-12-05 06:31:41 26 4
gpt4 key购买 nike

在我的 React.Component 实例的 componentDidMount 中,我有一个 fetch() 在响应调用时调用 setState.

我可以模拟请求并使用 sinon 进行响应,但我不知道 fetch 何时会解决它的 promise 链。

componentDidMount() {
fetch(new Request('/blah'))
.then((response) => {
setState(() => {
return newState;
};
});
}

在我使用 jestenzyme 的测试中:

it('has new behaviour from result of set state', () => {
let component = mount(<Component />);

requests.pop().respond(200);

component.update() // fetch() has not responded yet and
// thus setState has not been called yet
// so does nothing

assertNewBehaviour(); // fails

// now setState occurs after fetch() responds sometime after
});

我是否需要刷新 Promise 队列/回调队列或类似的东西?我可以在超时的情况下重复检查 newBehaviour,但这不太理想。

最佳答案

最好的答案似乎是使用 container pattern并从具有分离关注点的容器类中传递 API 数据,并分别测试组件。这允许被测组件简单地将 API 数据作为 props 并使其更易于测试。

关于javascript - 等待 fetch() 解析使用 Jest 进行 React 测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51699313/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com