首页 > 解决方案 > 测试数组适用于 toEqual 但不适用于 toBe

问题描述

我正在测试一个数组是否是我期望它使用的 toBe()。它通过toEqual(),但这不如检查好,toBe()因为我不希望返回的内容有任何错误空间。

我已经尝试过使用toEqual();的解决方法。然而,虽然它本身有效,但我也想toBe通过,因为我不想犯错。

getAssignedChildren = () => {
    const { parent, allChildren } = this.state;
    const { children: assignedChildren } = parent || {};
    const assignedChildNames = [];

    if (!assignedChildren) {
        return [];
    }

    assignedChildren.forEach((assignedChildId) => {

        const childData = allChildren.find(
            (child) => child.childId === assignedChildId,
        );
        assignedChildNames.push(childData.childName);
    });

    return assignedChildNames;
};    





it("should get the assigned children for a given parent, push the 
names of said children into an array, and display the names of the 
children on the corresponding parent\b's detail page", () => {
    const { children } = parent;
    const { records } = allChildren;
    const props = {
        someStore,
    };

// allChildren is an imported mock data object
    const wrapper = createWrapper(ParentDetails, props, true);
    wrapper.setState({
        parent: { children },
        allChildren: records,
    });
    wrapper.getAssignedChildren();

    // TODO: Refactor toEqual to toBe in order to apply stricter 
equality checking
// for reference, the mock data object causes there to be a matched 
child-to-parent array to have a length of 5
// I need this toEqual to be a toBe
    expect(wrapper.getAssignedChildren()).toEqual([
        records[0].childName,
        records[1].childName,
        records[2].childName,
        records[3].childName,
        records[4].childName,
    ]);

    expect(children.length).toEqual(wrapper.getAssignedChildren().length);

测试通过 toEqual。然而,toBe 说:

预期 ['child1', 'child2', 'child3', 'child4', 'child5'] 但得到 ['child1', 'child2', 'child3', 'child4', 'child5']。控制台错误消息显示:比较值没有视觉差异。请注意,您正在使用更严格的toBe匹配器测试相等性Object.is。仅对于深度相等,请toEqual改用。

标签: reactjsjestjs

解决方案


Jest 文档说明如下:

toBe 使用 Object.is 来测试完全相等。如果要检查对象的值,请改用 toEqual。

Object.is给出 2 个值是否相同。如果是数组,它们是否具有相同的引用。这就是为什么你需要使用toEqualto recursively checks every field of an object or array.

文档链接:https ://jestjs.io/docs/en/using-matchers

Object.is:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is _


推荐阅读