在不同浏览器上测试从对象删除值的问题

Troubles with testing delete value from object on different browsers

我需要测试从哈希中删除:

store = { 'a': 4 }
delete store['a']
expect(store['a']).toBeUndefined()

此测试在 chrome 上通过,但在 Firefox 中未通过。我得到:

Expected null not to be defined.

如何避免这个错误?

您正在测试错误的条件,因此 Chrome 和 Firefox 是否返回不同的值并不重要(但请参阅下文)。考虑一下:

store = { a: 11 }
store['a'] = undefined

这会给你一个 store['a']undefinedstore 仍然会有 'a' 作为键。

如果您想检查 delete 是否删除了 属性,请准确地说:

expect('a' of store).toBe(false)

CoffeeScript 的 of 运算符是 JavaScript 的 in 运算符并且来自 fine manual:

Using in with deleted or undefined properties

If you delete a property with the delete operator, the in operator returns false for that property.
[...]
If you set a property to undefined but do not delete it, the in operator returns true for that property.

这正是您要测试的行为。


郑重声明,当我说:

store = { 'a': 4 }
delete store['a']
console.log store['a']

我在最新的 Firefox 中得到 undefined