【发布时间】:2019-12-30 20:11:16
【问题描述】:
我正在测试一个数组是否是我期望它使用的
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']。控制台错误消息显示:比较值没有视觉差异。请注意,您正在使用
Object.is与更严格的toBe匹配器测试相等性。仅对于深度相等,请改用toEqual。
【问题讨论】:
-
正如它所说的
toBe正在使用Object.is,只有当数组引用相等时才会返回true。toEqual是这里要用到的 -
toBe与===基本相同。一旦你在你的方法中创建了一个新数组(顺便说一句,你应该使用map而不是forEach),toBe不能通过。