了解 comparison operators === and == 之间的差异后在 Javascript 中,我很惊讶 Jasmine 的平等概念与任何一个都不对应。例如,以下测试套件中的所有陈述都是正确的:
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
>)?
最佳答案
DSL jasmine 具有这种平等的概念,因为 javascript 中的平等可以是 confusing并在测试中readabilty很重要。看来在设计 Jasmine 时他们决定采用underscore.js平等观念。
要回答 Jasmine toEqual
是如何指定的,您可以在 source 中看到在 github 上。
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() ,它又来自 matchersUtil函数内部使用 eq
函数。
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;
...
}
};
关于javascript - Jasmine expect().toEqual()操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29633628/