用 jasmine .toEqual 比较两个不同的对象,一个对象是空的,另一个对象有一个键是一个符号,为什么说它们相等?

Compare two different objects with jasmine .toEqual, and one object is empty and the other has a key that is a symbol, why does it say they are equal?

这是我的期望声明

const otherObject = { [Symbol('what')]: { key: 'value' } };
expect({}).toEqual(otherObject); // succeeds

预期是测试失败。

为什么 jasmine 报告此测试成功?我正在使用 jasmine@3.5

这里是codesandboxhttps://codesandbox.io/s/floral-platform-rceq0

目前无法使用 Symbol 作为密钥。当 jasmine 进行比较时,它会尝试获取对象的 keys,参见 jasmine.js#L4551, the function used to extract the keys use Object.keys, see jasmine.js#L4587

看下面的例子

const otherObject = { [Symbol('what')]: { key: 'value' } };
console.log(Object.keys(otherObject)); // ouput []

因此,当 jasmine 运行 比较 expect({}).toEqual(otherObject); 时,它正在比较 {} 使用深度相等比较是否等于 {},并且它是true,就是比较两个空对象,字面意思。

使用以下应该失败的示例也不会起作用,但它通过了:

const mySymbol = Symbol('what');
const otherObject = { [mySymbol]: { key: 'value' } };
expect(otherObject).toEqual(
  jasmine.objectContaining({ [mySymbol]: { key: 'value2' } })
);

因此,您可以使用 Object.getOwnPropertySymbols 迭代您的对象并为每个值写一个期望值。

或者,您可以向 Jasmine 团队提出功能请求,以便他们考虑验证 Symbols 而不仅仅是密钥。

https://github.com/jasmine/jasmine/issues

希望对您有所帮助