Checking for Object Equality in TypeScript

I'm working on a TypeScript vector library and encountered my first failed test.

The issue revolves around object equality in TypeScript/JavaScript, and despite searching through TypeScript's official documentation (http://www.typescriptlang.org/Handbook#classes), I couldn't find a solution to make the test pass.

Can anyone offer some guidance?

Here is the snippet of 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;

Additionally, here is the unit test for this 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));
  });
});

Executing the test leads to 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 }).

Answer №1

The test case you provided is functioning properly. You can view it passing on jsfiddle by clicking here.

Upon closer inspection, it appears that in your original code, toBe() was mistakenly used instead of toEqual(), as indicated by the error message stating "to be" rather than "to equal":

Expected Object({ a: 789, b: 321 }) to be Object({ a: 789, b: 321 }).

Using toBe() compares the references of the two objects (i.e., ===), which obviously does not match. It is recommended to use toEqual() for a thorough comparison of values.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using React along with TypeScript to specify the type of useState as an object containing key/value pairs of strings

I'm currently working in React with typescript and attempting to set the type of useState as an object containing string key/value pairs. Despite searching on SO, I haven't found a solution yet. I've experimented with <{ [key: string]: s ...

The tRPC setData hook is limited in its ability to access all data necessary for optimistic UI updates

As I integrate mutations using tRPC and React Query to optimistically update my UI upon adding a new item, I've encountered an issue. The problem lies in the query I'm updating, which requires specific properties like auto-generated IDs or datab ...

What are the advantages of utilizing the HttpParams object for integrating query parameters into angular requests?

After exploring different ways to include query parameters in HTTP requests using Angular, I found two methods but struggled to determine which one would be the most suitable for my application. Option 1 involves appending the query parameters directly to ...

The options passed to createReadStream in TypeScript do not accept {start: 90, end: 99}

After updating to TypeScript 1.6.2, I encountered an issue with my call to createReadStream(). The problem arises because the type definition in node.d.ts does not recognize 'start' and 'end' in the options parameter. var st = fs.crea ...

What is preventing me from utilizing TouchEvent in Safari browser?

Recently, while working on a project utilizing Angular 8, I encountered an issue regarding touch event handling. In my code, I had a handler setup like this: @HostListener('touchend', ['$event']) onTouchend(event: TouchEvent) { eve ...

Exploring the Ways to Determine Array Type in Typescript Generics

I'm working with a method that looks like this: public select(fieldName: keyof TType) In this scenario, TType can potentially be an array type. If fieldName is called with a type of User[], I want to access the properties of User instead of the defa ...

When I try to reverse the words in a string, I am not receiving the desired order

Currently delving into TypeScript, I have set myself the task of crafting a function that takes in a string parameter and reverses each word within the string. Here is what I aim to achieve with my output: "This is an example!" ==> "sihT ...

Exploring the Enum Type in GraphQL Apollo Query

Within the server environment, I have defined the enum and query in the schema: type Query { hello: String! getData(dataType: DataType!): [DataPoint] } enum DataType { ACCOUNT, USER, COMPANY } ... Now, on the client s ...

What could be the reason for the component not receiving data from the service?

After attempting to send data from one component to another using a service, I followed the guidance provided in this answer. Unfortunately, the data is not being received by the receiver component. I also explored the solution suggested in this question. ...

Filtering data in TypeScript from a different component with the filter function

Currently, I am in the process of creating a filter function for a table. The table header and table body are separate components - with one responsible for filtering the data and the other for displaying it. User input is stored in the Table Header Compo ...

Show a condensed version of a lengthy string in a div using React TS

I've been tackling a React component that takes in a lengthy string and a number as props. The goal of the component is to show a truncated version of the string based on the specified number, while also featuring "show more" and "show less" buttons. ...

Error in Angular 5: Google Maps not defined

Having trouble implementing Google Maps on my Angular 5 app. Upon loading the view, I am encountering this error in the JavaScript console: LoginComponent_Host.ngfactory.js? [sm]:1 ERROR ReferenceError: google is not defined at LoginComponent.ngAfterVie ...

Passing a class as a parameter in Typescript functions

When working with Angular 2 testing utilities, I usually follow this process: fixture = TestBed.createComponent(EditableValueComponent); The EditableValueComponent is just a standard component class that I use. I am curious about the inner workings: st ...

Setting up d3 to function properly with Angular2 and TypeScript

Attempting to integrate the d3 library into an Angular 2 TypeScript project. I installed d3 using npm install d3 and the typings using typing install d3 --save, but when trying to start the local server for the project (tsc && concurrently "npm ru ...

Tips for showcasing all values in a nested array

In my Vue application, I am dealing with a nested array where users can select one date and multiple times which are saved as one object. The challenge I am facing now is how to display the selected date as a header (which works fine) and then list all the ...

Transforming JavaScript to TypeScript in Angular: encountering error TS2683 stating that 'this' is implicitly of type 'any' due to lacking type annotation

While in the process of migrating my website to Angular, I encountered an error when attempting to compile the JS into TS for my navbar. After searching around, I found similar issues reported by other users, but their situations were not quite the same. ...

Exploring ways to display all filtered chips in Angular

As a new developer working on an existing codebase, my current task involves displaying all the chips inside a card when a specific chip is selected from the Chip List. However, I'm struggling to modify the code to achieve this functionality. Any help ...

Merging two arrays concurrently in Angular 7

When attempting to merge two arrays side by side, I followed the procedure below but encountered the following error: Cannot set Property "account" of undefined. This is the code in question: acs = [ { "account": "Cash In Hand", ...

Building a TTL based schema in NestJs with MongooseIn this guide, we will explore

In my NestJs(TypeScript) project, I am attempting to create a self-destructing schema using the mangoose and @nestjs/mongoose libraries. Unfortunately, I have been unable to find a clear way to implement this feature. While I know how to do it in an expres ...

The type does not contain a property named `sort`

"The error message 'Property sort does not exist on type (and then shoes4men | shoes4women | shoes4kids)' pops up when attempting to use category.sort(). I find it puzzling since I can successfully work with count and add a thousand separato ...