打字稿中的对象相等 [英] Object Equality in Typescript

查看:90
本文介绍了打字稿中的对象相等的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要在打字稿中的向量上创建一个lib。我的第一个测试失败了:)。

I'm creating a lib on vectors in typescript. My very first test failed:).

它与TypeScript / JavaScript中的对象相等性有关,但是我找不到绿色的方法。在typescript的官方文档 http://www.typescriptlang.org/Handbook#classes。

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.

有人可以帮我吗?

这是源代码。

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));
  });
});

执行时获得以下错误

Failures: 
1) vector should add another vector
1.1) Expected Vector({ x: 3, y: 4 }) to be Vector({ x: 3, y: 4 }).


推荐答案

您的测试用例应该可以工作。 此处传递了jsfiddle

Your test case should work. Here it is passing on jsfiddle.

但是,似乎您的实际代码使用的是 toBe()而不是 toEqual(),因为失败消息显示成为 ,而不是等于

However, it seems your actual code was using toBe() instead of toEqual(), since the failure message says "to be" and not "to equal":


期望的向量({x:3,y:4})成为向量({x:3,y:4})。

Expected Vector({ x: 3, y: 4 }) to be Vector({ x: 3, y: 4 }).

使用 toBe()将检查两个对象的身份是否相同(即 === ),但显然不是。您肯定希望 toEqual()可以对值进行深度比较。

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.

这篇关于打字稿中的对象相等的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆