【问题标题】:In Enzyme how to wait for an API call in the componentDidMount method?在 Enzyme 中,如何在 componentDidMount 方法中等待 API 调用?
【发布时间】:2021-01-29 02:19:00
【问题描述】:

我们有一个使用Enzyme 挂载的 React 组件:

const component = mount(<App/>);

组件在componentDidMount 上加载数据,我们用nock 模拟:

nock('http://localhost:3100').get(`/api/data`).reply(200, DATA...);

我们要测试组件内标签的value。但是,value 仅在通过 fetch 调用加载数据后才会填充。在编写期望之前,我们如何等待 fetch 调用完成:

expect(...

【问题讨论】:

  • 您需要链接一个 fetch 返回的承诺。请提供组件的代码。

标签: reactjs jestjs enzyme nock


【解决方案1】:

您必须执行以下操作:

Promise
    .resolve(mounted)
    .then(() => mounted.update())
    .then(() => {
        expect(label === value); // Just using pseudocode here to denote where to write the expect statement
    })

你可能仍然会遇到不正确的行为,在这种情况下你可以检查this线程

【讨论】:

    猜你喜欢
    • 2019-12-06
    • 1970-01-01
    • 2022-01-18
    • 1970-01-01
    • 2019-01-22
    • 2019-07-14
    • 2021-02-25
    • 1970-01-01
    • 2015-11-09
    相关资源
    最近更新 更多