typescript 打字稿中的对象平等
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35903941/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Object Equality in Typescript
提问by Hui Wang
I'm creating a lib on vectors in typescript. My very first test failed:).
我正在打字稿中的向量上创建一个库。我的第一次测试失败了:)。
It's related to object equality in TypeScript/JavaScript but I can't find a way to make the test green. No object equality is mentioned in typescript's official doc http://www.typescriptlang.org/Handbook#classes.
它与 TypeScript/JavaScript 中的对象相等性有关,但我找不到使测试变绿的方法。typescript 的官方文档http://www.typescriptlang.org/Handbook#classes 中没有提到对象相等。
Could someone please give me a hand ?
有人可以帮我一把吗?
This is the source code.
这是源代码。
class Vector {
x: number;
y: number;
constructor(x: number, y: number) {
this.x = x;
this.y = y;
}
add(that: Vector) {
return new Vector(this.x + that.x, this.y + that.y);
}
}
export = Vector;
Then I have a unit test on this class as follows
然后我对这个类进行了单元测试,如下所示
var Vector = require("../lib/vector")
describe("vector", function () {
it("should add another vector", function () {
var v1 = new Vector(1, 1);
var v2 = new Vector(2, 3);
expect(v1.add(v2)).toEqual(new Vector(3, 4));
});
});
When executed obtains the following error
执行时出现如下错误
Failures:
1) vector should add another vector
1.1) Expected Vector({ x: 3, y: 4 }) to be Vector({ x: 3, y: 4 }).
采纳答案by Aaron Beall
Your test case should work. Here it is passing on jsfiddle.
您的测试用例应该可以工作。在这里它传递 jsfiddle。
However, it seems your actual code was using toBe()
instead of toEqual()
, since the failure message says "to be"
and not "to equal"
:
但是,您的实际代码似乎正在使用toBe()
而不是toEqual()
,因为失败消息说"to be"
而不是"to equal"
:
Expected Vector({ x: 3, y: 4 }) to beVector({ x: 3, y: 4 }).
预期 Vector({ x: 3, y: 4 })为Vector({ x: 3, y: 4 })。
Using toBe()
will check that the identity of the two objects are the same (ie ===
), which they obviously are not. You definitely want toEqual()
which does a deep comparison of values.
UsingtoBe()
将检查两个对象的身份是否相同(即===
),而它们显然不是。您肯定想要toEqual()
对值进行深入比较。
回答by basarat
TypeScript object equality is the same as JavaScript object equality. This is because TypeScript is just JavaScript.
TypeScript 对象相等性与 JavaScript 对象相等性相同。这是因为TypeScript 只是 JavaScript。