打字稿中的对象平等
Object Equality in Typescript
我正在用打字稿创建一个向量库。我的第一次测试失败了:).
它与TypeScript/JavaScript中的对象相等性有关,但我找不到使测试绿色的方法。 typescript 的官方文档中没有提到对象相等 http://www.typescriptlang.org/Handbook#classes.
有人可以帮帮我吗?
这是源代码。
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;
然后我对这个class进行单元测试如下
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));
});
});
执行时得到如下错误
Failures:
1) vector should add another vector
1.1) Expected Vector({ x: 3, y: 4 }) to be Vector({ x: 3, y: 4 }).
TypeScript 对象相等与 JavaScript 对象相等相同。这是因为 TypeScript is just JavaScript.
您的测试用例应该可以工作。 Here it is passing on jsfiddle.
但是,您的实际代码似乎使用的是 toBe()
而不是 toEqual()
,因为失败消息显示的是 "to be"
而不是 "to equal"
:
Expected Vector({ x: 3, y: 4 }) to be Vector({ x: 3, y: 4 }).
使用toBe()
将检查两个对象的标识是否相同(即===
),而它们显然不是。您肯定想要 toEqual()
对值进行深入比较。
我正在用打字稿创建一个向量库。我的第一次测试失败了:).
它与TypeScript/JavaScript中的对象相等性有关,但我找不到使测试绿色的方法。 typescript 的官方文档中没有提到对象相等 http://www.typescriptlang.org/Handbook#classes.
有人可以帮帮我吗?
这是源代码。
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;
然后我对这个class进行单元测试如下
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));
});
});
执行时得到如下错误
Failures:
1) vector should add another vector
1.1) Expected Vector({ x: 3, y: 4 }) to be Vector({ x: 3, y: 4 }).
TypeScript 对象相等与 JavaScript 对象相等相同。这是因为 TypeScript is just JavaScript.
您的测试用例应该可以工作。 Here it is passing on jsfiddle.
但是,您的实际代码似乎使用的是 toBe()
而不是 toEqual()
,因为失败消息显示的是 "to be"
而不是 "to equal"
:
Expected Vector({ x: 3, y: 4 }) to be Vector({ x: 3, y: 4 }).
使用toBe()
将检查两个对象的标识是否相同(即===
),而它们显然不是。您肯定想要 toEqual()
对值进行深入比较。