我在jest测试中基于给定的值创建了两个对象,并期望它们是相等的,除了属性uuid,它是为每个对象独立生成的。
uuid可以多次深度嵌套。例如:
const object1 = { uuid: '5435443', name: 'xxx', branches: [{ uuid: '643643', children: [{ uuid: '65654' /* and so on */ }] }];
const object2 = { uuid: '7657657', name: 'xxx', branches: [{ uuid: '443444', children: [{ uuid: '09809' }] }];如何比较对象,忽略uuid属性?
发布于 2021-08-23 11:25:19
您可以先删除uuid,然后再比较它们。
const object1 = { uuid: '5435443', name: 'xxx', branches: [{ uuid: '643643', children: [{ uuid: '65654' /* and so on */ }] }]};
const object2 = { uuid: '7657657', name: 'xxx', branches: [{ uuid: '443444', children: [{ uuid: '09809' }] }]};
const removeUuid = o => {
if (o) {
switch (typeof o) {
case "object":
delete o.uuid;
Object.keys(o).forEach(k => removeUuid(o[k]));
break;
case "array":
o.forEach(a => removeUuid(a));
}
}
}
removeUuid(object1);
removeUuid(object2);
expect(object1).toBe(object2);发布于 2021-08-23 10:21:22
您可以使用expect.any忽略uuid属性。只需确保属性存在,并且uuid是一个字符串:
describe("Compare 2 objects", () => {
it("should ...", () => {
const actual = { uuid: '5435443', name: 'xxx', branches: [{ uuid: '643643', children: [{ uuid: '65654' }] }] };
const expected = {
uuid: expect.any(String), // <--
name: 'xxx',
branches: [{ uuid: expect.any(String), children: [{ uuid: expect.any(String) }] }]
};
expect(actual).toEqual(expected);
});
});发布于 2021-08-23 10:51:52
我通过以下解决方案成功地实现了这一点:
const object1 = { uuid: '5435443', name: 'xxx', branches: [{ uuid: '643643', children: [{ uuid: '65654' /* and so on */ }] }] };
const object2 = { uuid: '7657657', name: 'xxx', branches: [{ uuid: '443444', children: [{ uuid: '09809' }] }] };
const compareExcludeKeys = (object1, object2, excludeKeys = []) => {
if (Object.keys(object1).length !== Object.keys(object2).length) return false;
return Object.entries(object1).reduce((isEqual, [key, value]) => {
const isValueEqual = typeof value === 'object' && value !== null
? compareExcludeKeys(value, object2[key], excludeKeys)
: excludeKeys.includes(key) || object2[key] === value;
return isEqual && isValueEqual;
}, true);
};
console.log(compareExcludeKeys(object1, object2, ['uuid']));
https://stackoverflow.com/questions/68890700
复制相似问题