reactjs - 测试数组适用于 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
改用。
解决方案
Jest 文档说明如下:
toBe 使用 Object.is 来测试完全相等。如果要检查对象的值,请改用 toEqual。
Object.is
给出 2 个值是否相同。如果是数组,它们是否具有相同的引用。这就是为什么你需要使用toEqual
to 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 _
推荐阅读
- bitbucket-pipelines - Bitbucket 管道 Maven 缓存未缓存所有工件
- amazon-web-services - CNAME 记录指向外域
- neo4j - 用java在neo4j中同时更新多个相关节点
- python - Django - 在模板中插入代码的中间件
- amazon-quicksight - AWS Quicksight 和多个向下钻取
- if-statement - 汇编程序中的条件跳转总是给出相同的结果
- c++ - 当它的元素是对象时使用 STL DS
- swift - 创建一个包含 3 个项目的导航栏
- compilation - 为什么未执行的编译时代码会增加 Raku 的字节码大小?它会降低运行时性能吗?
- r - 防止 R 闪亮 UI 中的占位符空间