在componentDidMount中获取时如何测试反应组件?

jus*_*rld 5 unit-testing reactjs jestjs enzyme

我有一个组件,我fetchcomponentDidMount. 我想对此进行测试,而且我必须诚实:我根本不清楚如何进行。

关键是似乎没有一种“标准”的方式来进行。基本上,我发现更令人困惑的是:

  • 如何模拟:显然,您可以使用Jestjest-fetch-mock模拟异步调用。
  • 如何管理生命周期和构建测试:
    • 这篇文章中,方法 3 解释了如何使用酶和 jest-fetch-mock 实现测试。
    • 这个文章是如何仅开玩笑测试异步调用解释。

我不太清楚什么时候应该使用一种方法/库而不是另一种。

这是我的函数的简化版本:

componentDidMount() {
    fetch(URL, {
        method: 'GET',
    }).then(response => {
        if (response.ok) {
            return response.json();
        } else {
            throw new Error("Error loading data from " + URL);
        }
    }).then(data => {
        if (!_.isEmpty(data)) {
            this.setState({
                data: data,
            });
        } else {
            throw new Error("Invalid data from " + URL);
        }
    }).catch(error => {
        console.log(URL + ' error: ', error);
        this.setState({error});
    });

    const payload = {...};

    fetch(URL2, {
        method: 'POST',
        body: JSON.stringify(payload),
    }).then(response => {
        if (response.ok) {
            return response.json();
        } else {
            throw new Error("Error loading data from " + URL2);
        }
    }).then(data => {
        if (!_.isEmpty(data2)) {
            this.setState({
                data2: data2
            });
        } else {
            throw new Error("Invalid data from " + URL2);
        }

    }).catch(error => {
        this.setState({error, isLoading: false});
    });
Run Code Online (Sandbox Code Playgroud)

}

我想测试的是:

  • 假设 fetch ( GET) 进行得很好,测试更新的state尊重我想要的形式(所以两种情况data都是好的/坏的)。
  • 假设获取失败,测试state更新为error
  • 请注意,我也想对第二次提取执行类似的测试。

当然,我需要一个模拟机制来模拟两个答案(forGETPOST操作),但不清楚我应该如何做,或者如何测试结果。

Joã*_*aça 3

您不需要模拟 api 调用。fetch有自己的库测试,因此您无需测试是否fetch有效。但如果您确实需要测试您的方法,您可以使用jest- https://facebook.github.io/jest/docs/en/asynchronous.html。忘记玩笑取笑吧。您可以测试:

  1. 该方法被componentDidMount调用了吗?
  2. yourMethod称为?
  3. 完成后yourMethod,变化发生了吗?(你的新状态是你所期望的吗?)

请记住不要测试库本身,或者深入到组件树。您应该只进行原子测试。一心一意。

现在:

您可以使用async/await或仅测试获取本身。首先,您应该将这些fetch“es”抽象为它们自己的方法。现在。如果您所做的只是连接承诺,并且如果您正确设置了状态,那么您只需要在测试文件上解决该承诺,并在其回调上检查状态是否更改为您想要的。

同样,这有您需要知道的所有内容:https ://facebook.github.io/jest/docs/en/asynchronous.html#promises

如果您还需要一项资源,请访问:https://codereviewvideos.com/course/react-redux-and-redux-saga-with-symfony-3/video/testing-javascript-s-fetch-with-jest -快乐之路

  • 抱歉,在您提供给我的所有文档中,没有描述如何测试组件状态。那么,测试隔离的 fetch 调用的目的是什么?由于我们模拟了数据,因此我们只是测试返回的数据是否是我们模拟的数据。不是很有用。 (2认同)