gpt4 book ai didi

javascript - Jasmines expect().toEqual() 操作

转载 作者:行者123 更新时间:2023-11-29 21:50:18 25 4
gpt4 key购买 nike

在了解了 comparison operators === and == 之间的差异之后在 Javascript 中,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)?

最佳答案

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 - Jasmines expect().toEqual() 操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29633628/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com