我们开发了一组相当大的自定义 jasmine 匹配器,有助于使我们的代码更简洁并避免代码重复。我注意到一些自定义 jasmine 匹配器使用 ===
相等性测试和一些 jasmine.matchersUtil.equals
。示例:
toHaveHandCursor: function() {
return {
compare: function(actual) {
return {
pass: actual.getCssValue("cursor").then(function(cursor) {
return cursor === "pointer";
})
};
}
};
},
toBeActive: function() {
return {
compare: function(elm) {
return {
pass: protractor.promise.all([
elm.getId(),
browser.driver.switchTo().activeElement().getId()
]).then(helpers.spread(function (currentElementID, activeElementID) {
return jasmine.matchersUtil.equals(currentElementID, activeElementID);
})),
message: "Element is not active."
};
}
};
}
问题:
jasmine.matchersUtil.equals
和 ===
相等性测试有什么区别,应该首选哪种方法?
换句话说,一般来说,如果我们只使用 ===
会有风险吗?
最佳答案
据我所知,这里是我为 jasmine.matchersUtil.equals
和 ===
找到的一些东西:
根据定义,===
根据其值
和类型
比较两个实体。它是一个 strict
比较运算符。例如:
2 === 2 //true
2 === 3 //false
2 === '2' //false
0 === -0 //true
(Sample scenario where +0, 0 and -0 can appear)
另一方面,jasmine.matchersUtil.equals
是基于 underscorejs 的 _.isEqual
逻辑实现的,并根据判断是否相等的逻辑来测试相等性传递给它的实体应该被认为是相等的,即使它们的 types
不同。像这样的 -
jasmine.matchersUtil.equals(2, 2) //true
jasmine.matchersUtil.equals(2, 3) //false
jasmine.matchersUtil.equals(2, '2') //false
jasmine.matchersUtil.equals(0, -0) //false
这是从 git repo 中摘录的 -
// Identical objects are equal. `0 === -0`, but they aren't identical.
if (a === b) { return a !== 0 || 1 / a == 1 / b; }
编辑:
jasmine.matchersUtil.equals()
的额外优势是我们实际上可以实现我们自己的自定义相等性测试器,这样就可以避免一些被认为会产生问题的场景。这是与以下示例一起使用的自定义相等性测试器的示例 -
var customTester = function(first, second) {
return first == second;
};
几个场景-
假设如果需要检查元素文本是否为空或是否具有某些特定值,并且有为其开发的自定义 jasmine 匹配器,那么 -
"5" === 5 //if operation on elem returns "5" then custom matcher gives false jasmine.matchersUtil.equals("5", 5, customTester) //true when implemented with custom equality testers undefined === null //if operation on elem returns undefined then custom matcher gives false jasmine.matchersUtil.equals("", null, customTester) //true when implemented with custom equality testers NaN === NaN //if operation on elem returns NaN then custom matcher gives false jasmine.matchersUtil.equals(NaN, NaN) //true
使用自定义匹配器更容易检查对象的相等性。例如:
{name: 'hill'} === {name: 'hill'} //false jasmine.matchersUtil.equals({name: 'hill'}, {name: 'hill'}) //true
只要我们知道可能会出现与预期值不同的值,或者可能出现上述任何情况,我们总是会使用自定义匹配器。如果保证期望是单个值,那么使用 ===
是有意义的。希望能帮助到你。
关于javascript - jasmine.matchersUtil.equals 与 ===,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33114417/