Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Object Equality in Typescript [duplicate]

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.

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 }).
like image 574
Hui Wang Avatar asked Mar 09 '16 22:03

Hui Wang


People also ask

How do you duplicate an object in TypeScript?

To create a deep copy of an object in TypeScript, install and use the lodash. clonedeep package. The cloneDeep method recursively clones a value and returns the result. The cloneDeep method returns an object of the correct type.

Why are two identical objects not equal to each other?

Objects are not compared by value: two objects are not equal even if they have the same properties and values. This is true of arrays too: even if they have the same values in the same order. var a = {}; // The variable a refers to an empty object. var b = a; // Now b refers to the same object.

Can two objects be equal JavaScript?

In JavaScript, we cannot directly compare two objects by equality operators (double equals == or triple equals ===) to see whether they are equal or not. Comparing two objects like this results in false even if they have the same data.


1 Answers

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

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

Expected Vector({ x: 3, y: 4 }) to be 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.

like image 190
Aaron Beall Avatar answered Oct 13 '22 00:10

Aaron Beall