Jasmine有内置的匹配器toBe
和toEqual
。如果我有一个这样的对象:
function Money(amount, currency){
this.amount = amount;
this.currency = currency;
this.sum = function (money){
return new Money(200, "USD");
}
}
并尝试比较new Money(200, "USD")
和sum的结果,这些内置的匹配器将不会像预期的那样工作。我已经设法实现了一个基于自定义equals
method和自定义匹配器的变通方法,但它似乎需要做很多工作。
在Jasmine中比较对象的标准方法是什么?
发布于 2013-07-05 16:45:02
我也在寻找同样的东西,并找到了一种现有的方法来做到这一点,而不需要任何自定义代码或匹配器。使用toEqual()
。
发布于 2015-02-12 03:50:57
如果你想比较部分对象,你可以考虑:
describe("jasmine.objectContaining", function() {
var foo;
beforeEach(function() {
foo = {
a: 1,
b: 2,
bar: "baz"
};
});
it("matches objects with the expect key/value pairs", function() {
expect(foo).toEqual(jasmine.objectContaining({
bar: "baz"
}));
});
});
发布于 2013-05-07 03:36:21
这是预期的行为,因为在JavaScript中一个对象的两个实例是不同的。
function Money(amount, currency){
this.amount = amount;
this.currency = currency;
this.sum = function (money){
return new Money(200, "USD");
}
}
var a = new Money(200, "USD")
var b = a.sum();
console.log(a == b) //false
console.log(a === b) //false
对于干净的测试,您应该编写自己的匹配器来比较amount
和currency
beforeEach(function() {
this.addMatchers({
sameAmountOfMoney: function(expected) {
return this.actual.currency == expected.currency && this.actual.amount == expected.amount;
}
});
});
https://stackoverflow.com/questions/16401237
复制相似问题