在了解Javascript中comparison operators === and ==之间的差异后,我很惊讶Jasmines的平等概念与任何一个都不对应。例如,以下测试套件中的所有语句都是真的:
describe('Jasmine asserted equality of objects', function() {
it('is different from ===- and ==-equality', function() {
var x = {};
var y = {};
expect(x === y).toBeFalsy();
expect(x == y).toBeFalsy();
expect(x).toEqual(y);
});
it('seems to imply element-wise equality', function() {
var x = {'name': 'value'};
var y1 = {'name': 'values'};
var y2 = {'names': 'value'};
var y3 = {'name': 'value'};
expect(x).not.toEqual(y1);
expect(x).not.toEqual(y2);
expect(x).toEqual(y3);
});
it('does not imply equality of the respective prototypes', function() {
var x = {};
var y = Object.create(x);
var pr = Object.getPrototypeOf;
expect(x).toEqual(y);
expect(pr(pr(x))).not.toEqual(pr(pr(y)));
});
});
不幸的是,我无法找到Jasmine的任何官方API文档。众所周知的introduction page仅提供示例,我发现的大多数其他来源都讨论了custom matchers的===和==或Jasmines概念的区别。
但是,我的主要问题如下: Jasmines如何指定toEqual
?此外,我对引入这种新的平等概念的理由感兴趣:为什么或哪个案例expect(x).toEqual(y)
比x === y
(或x == y
)更合适?
答案 0 :(得分:1)
DSL jasmine具有这种平等概念,因为javascript中的相等性可以是confusing,而在readabilty测试中则很重要。看来,在设计茉莉花时,他们决定采用underscore.js平等概念。
要回答如何指定jasmines toEqual
,您可以在github上的source中看到。
getJasmineRequireObj().toEqual = function() {
function toEqual(util, customEqualityTesters) {
customEqualityTesters = customEqualityTesters || [];
return {
compare: function(actual, expected) {
var result = {
pass: false
};
result.pass = util.equals(actual, expected, customEqualityTesters);
return result;
}
};
}
return toEqual;
};
正如我们在上面看到的那样使用util.equals(),而util.equals()又来自内部使用eq
函数的matchersUtil函数。
getJasmineRequireObj().matchersUtil = function(j$) {
// TODO: what to do about jasmine.pp not being inject? move to JSON.stringify? gut PrettyPrinter?
return {
equals: function(a, b, customTesters) {
customTesters = customTesters || [];
return eq(a, b, [], [], customTesters);
},
...
// Equality function lovingly adapted from isEqual in
// [Underscore](http://underscorejs.org)
function eq(a, b, aStack, bStack, customTesters) {
var result = true;
...
}
};