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

Rendering a React/Material UI class based on the state variable in a conditional manner

I am currently working on building a basic navbar setup using React and Material UI. I have encountered an issue where React-Router-Dom does not seem to be functioning within this particular project, and implementing it would be excessive for the simple ta ...

New Authentication: The sign-in feature will redirect to /api/auth/error

Currently implementing Google sign-in functionality on my Next.js 13 app using Next-auth. I have utilized the signIn() function as described in the documentation here. However, upon calling the signIn() function, I am unexpectedly redirected to http://loca ...

How can I create interfaces for deeply nested objects in TypeScript?

Check out my current JSON data below: { "state_1": { "date": [ { 1000: { "size": 3, "count": 0 } }, { 1001: { "size" ...

The upcoming router is not compatible with the NextPage type

I am currently working on introducing dynamic routing into an application that was originally designed with static routes. However, I am facing some confusion as I encounter TypeScript errors that are difficult for me to understand. Below is the code snipp ...

Angular button press

Recently, I started learning Angular and came across a challenge that I need help with. Here is the scenario: <button *ngIf="entryControlEnabled && !gateOpen" class="bottomButton red" (click)="openGate()">Open</button> <button *ngIf ...

Resolving conflict between a user-defined class name and a built-in class name

I am creating a TypeScript Map class that utilizes the built-in Map class along with generics. The problem arises when both classes have the same name. Is there a way to import the built-in Map using explicit namespace, similar to how it's done in Jav ...

What is the best way to selectively pass certain values to the args object?

Is there a way in TypeScript to pass only one argument into args and have other values be default without using "args = {}" or declaring defaults within the function to avoid issues with intellisense? function generateBrickPattern ( wallWidth: number, ...

Autodesk Forge serves as a hub for hosting dependencies on a nearby server

Our company has implemented an Angular/TypeScript version of the Forge Viewer, currently loading dependencies from Autodesk's server. To ensure these files are always accessible to our customers, we want to host them on our own servers. However, attem ...

Is there a way to inform TypeScript that an object can only return properties from values found within an array?

I am trying to ensure that the return object from a function in TypeScript only allows keys that correspond to string values present in an array passed as an argument to the function. The returned object should contain a subset of keys from a list of valid ...

Exploring the world of typescript with the power of ts-check

I'm having trouble figuring out how to work with a generic function using TypeScript's new ts-check feature. /** * @type {Reducer<IPoiState, any>} */ const poi = handleActions({ [ADD_BOOKMARK_START]: (state) => { return { ...sta ...

Bring in personalized tag to TypeScript

I am working on a TypeScript file to generate an HTML page. Within this code, I want to import the module "model-viewer" and incorporate it into my project. import * as fs from "fs"; import prettier from "prettier"; import React from "react"; import ReactD ...

Error: Typescript foreach loop encountering 'Expression yields void type'

Currently, I am working on setting up a cron job to monitor the completion of my tournaments and trigger some specific code upon completion. For reference, I came across this example: During deployment of my code, an error popped up as follows: ERROR: fu ...

Using `publishReplay()` and `refCount()` in Angular does not behave as anticipated when dealing with subscriptions across multiple components

I am currently investigating the functionality of publishReplay in rxjs. I have encountered an example where it behaves as expected: const source = new Subject() const sourceWrapper = source.pipe( publishReplay(1), refCount() ) const subscribeTest1 = ...

Navigating through the concept of passing objects by reference in child components of Angular 2+

Understanding that TypeScript uses object passing by reference can be challenging, especially when dealing with deep copy issues. This becomes particularly cumbersome when working within a theme. I recently encountered an issue with a component containing ...

extract keys and values from an array of objects

I would like assistance with removing any objects where the inspectionScheduleQuestionId is null using JS. How can we achieve this? Thank you. #data const data = [ { "id": 0, "inspectionScheduleQuestionId": 1, ...

Angular Material 2: Tips for Differentiating Multiple Sortable Tables in a Single Component

Greetings, esteemed members of the Stackoverflow community, As per the Angular Material 2 documentation, it is mentioned that you can include an mdSort directive in your table: Sorting The mdSort directive enables a sorting user interface on the colum ...

In Deno, it is possible to confirm that a variable is an instance of a String

I'm having trouble asserting instances of string in Deno: import { assertInstanceOf } from "https://deno.land/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="2642405050405e445e59445e">[email protected]</a& ...

Managing Observable<Person[]> in ng-bootstrap typeahead instead of Observable<string[]>: a complete guide

I'm new to Angular/Typescript and have a question. I recently tried out the example from Wikipedia in ng-bootstrap typeahead. Instead of using the Wikipedia call, I decided to use a custom REST service that has the following GET endpoint: GET /pers ...

Unable to perform a union operation that combines multiple enums into one

Here is a basic example: export enum EnumA { A = 'a', } export enum EnumB { A = 'b', } export class SomeEntity { id: string; type: EnumA | EnumB; } const foo = (seArray: SomeEntity[]) => { seArray.forEach((se) => { ...

The error message "TypeError: this.subQuery is not a function" is displayed

Whenever I execute the tests using jest, I consistently encounter the error message TypeError: this.subQuery is not a function pointing to a specific line in the testModelDb.test.ts file. In the tests/jest.setup.ts file: import 'reflect-metadata&apos ...