Jasmine encountered an error while trying to compare the same string: 'Expected the values to match.'

I'm encountering an error message, despite verifying that the strings are identical:

Expected { $$state : { status : 1, value : { customerNumber : 'customerNumber', name : 'name', userId : 'buId', customerType : 'type', address : 'displayAddress' } } } 
to equal { $$state : { status : 1, value : { customerNumber : 'customerNumber', name : 'name', userId : 'buId', customerType : 'type', address : 'displayAddress' } } }.
Error: Expected { $$state : { status : 1, value : { customerNumber : 'customerNumber', name : 'name', userId : 'buId', customerType : 'type', address : 'displayAddress' } } } to equal { $$state : { status : 1, value : { customerNumber : 'customerNumber', name : 'name', userId : 'buId', customerType : 'type', address : 'displayAddress' } } }.
        at C:/customerServiceSpec.js:70

The only discrepancy I can identify is a period at the end, though I suspect Jasmine adds it in the response. Here's my testing code snippet:

describe('CustomerService', () => {
    var mockUserSession: any = {};
    var testService any = {};
    var $q: ng.IQService;
    var createCustomerDetailsService;
    var customerDetailsService;
    var createResolvedPromise;
    var createRejectedPromise;
    var resolvePromises;

    var testResponse = {
        customers: {
            displayCustomerNumber: 'customerNumber',
            name: 'name',
            id: 'id',
            type: 'type',
            displayAddress: 'displayAddress'
        }
    };

    var serviceResponse={
        $$state: {
            status: 1,
            value: {
                customerNumber: 'customerNumber',
                name: 'name',
                id: 'id',
                customerType: 'type',
                address:'displayAddress'
            }
        }
    };

    var rootScope;

    beforeEach(() => {
        module('app.customer');

        inject(( _$q_, $injector) => {
            this.$q = _$q_;
            rootScope = $injector.get('$rootScope');

            createResolvedPromise = (result) => {
                return () => {
                    return this.$q.when(result);
                };
            };

            resolvePromises = () => {
                rootScope.$digest();
            };

            createCustomerDetailsService = () => {
                return new app.customer.CustomerService(
                    testService);
            };
        });

    });

    it('WILL search by customer ID and return a customers details', () => {
        var searchResponsePromise;

        testService.getCustomerDetails = jasmine.createSpy("getCustomerDetails").and.callFake(createResolvedPromise(testResponse));
        customerDetailsService = createCustomerDetailsService();
        searchResponsePromise = customerDetailsService.getCustomerDetails('12345678');
        resolvePromises();

        expect(searchResponsePromise).toEqual(serviceResponse);
    });
});

Below is the relevant excerpt from my service:

public getCustomerDetails(customerID:string): ng.IPromise<ICustomerDetails> {
    return this.testService.getCustomerDetails(customerID).then((customerResponse:ICustomerResult) => {

        var customer = customerResponse.customers;

        var customerDetailsResult:ICustomerDetails = {
            customerNumber: customer.displayCustomerNumber,
            name: customer.name,
            userId: customer.buId,
            customerType: customer.type,
            address: customer.displayAddress
        };

        return customerDetailsResult;
    });
}

Your assistance is greatly appreciated.

Answer №1

The reason for this occurrence is that JSON objects are distinct instances of objects, even though they hold identical data. To resolve this issue, you should implement the following:

expect(angular.equals(searchResponsePromise, serviceResponse)).toBe(true);

Answer №2

If you're interested in how to compare objects using AngularJS and Jasmine, check out this helpful resource on AngularJS + Jasmine: Comparing objects. The recommended approach is to utilize the expect(...).toEqual(...) method instead of expect(...).toBe(...). By using toEqual(), a deep comparison can be executed.

One of the key advantages of using toEqual() over the alternative method is that it provides more informative error messages when an assertion fails. For instance, if you use toBe(true) and it fails, the error message might only state 'expected false to be true', which may not be sufficient to identify and address the issue.

When using toEqual(), the deep comparison results in an assertion error that includes both the expected and actual objects serialized as strings. This feature greatly enhances the debugging process and makes it easier to rectify any discrepancies. :)

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

Website API: decouple backend and frontend functionality through an API

I am currently working on the development of a website and an app created through Cordova. The app will essentially mirror the functionalities of the website. The website is already established and heavily relies on JavaScript, with potential considerati ...

Encountering the error message "Received interpolation ({{}}) when an expression was expected" is a common issue when trying to interpolate tag attribute values within an ngFor loop

I've been working with a Devextreme's Datatable and my goal is to dynamically configure the table using a columns configuration array. The plan is to loop through this array using an ngFor and set column tags properties dynamically. Now, the bi ...

Incorporating external Angular 4 components within my custom components

For my project, I am attempting to incorporate jqWidgets Angular components: import { Component, ViewChild } from '@angular/core'; import 'jqwidgets-framework'; import { jqxTreeComponent } from "jqwidgets-framework/jqwidgets-ts/angula ...

Displaying angularJS ui-grid columns in a lazy manner

Is there a way to efficiently load columns as needed? I have a large dataset with 5k columns and 100k rows. My framework is angularjs 1.5.7 along with angular-ui-grid ^3.x. The grid performs well with 100k rows and 100 columns, but when trying to load ove ...

Converting PDF files to JSON in ASP.NET and transferring them to AngularJS using Base64 does not result in identical files

After encoding a PDF file as Base64 and assigning it to a property of my model object in ASP.NET WEB API, the JSON response is received by my AngularJS client application. However, upon saving the file, I noticed that the file size increases by one and 1/3 ...

How to dynamically load a component within a class-based Vue component

I am facing an issue with loading two components dynamically using an object map. Info (options-based) SearchBar (class-based) While it works for the options-based component, I encounter an error stating _currentTab is undefined when trying to load a si ...

Utilize Angular's grep or filter method to retrieve an object based on its unique identifier

I have a collection of Category objects stored as a JSON array in vm.data within my controller for an Angular repeater. Now, I want to access the SubCats within each category by using the 'Category' field in each SubCat. Below is a generic funct ...

Issues with cross-site scripting in testacular E2E tests and Angular developments

I am currently in the process of developing a web application using Java on the server side and Angular for the front end. I am facing challenges while setting up end-to-end tests with testacular. The tests are failing due to what seems to be cross-site sc ...

Utilizing Typescript to ensure property keys within a class are valid

Looking for advice to make a method more generic. Trying to pass Child class property keys as arguments to the Super.method and have Child[key] be of a Sub class. class Parent { method<T extends keyof this>(keys: T[]){ } } class Child extends P ...

AngularJS Uncaught ReferenceError: variable is not

I am facing an issue where I cannot retrieve a value from a function. I am performing REST requests for testing purposes and when trying to get a date, it always returns undefined. An Illustration $http.get('app/components/home/controller/test_calen ...

Analyzing elements within an array using Angular 4

I have an array filled with various Objects such as: [ {"id":1,"host":"localhost","filesize":73,"fileage":"2018-01-26 09:26:40"}, {"id":2,"host":"localhost","filesize":21,"fileage":"2018-01-26 09:26:32"}, {...} ] These objects are displayed in the fol ...

After successfully building with Vite, an error occurs stating "TypeError: can't convert undefined to object." However, during development with Vite, everything functions flawlessly

Currently, I am utilizing Vite in conjunction with React and Typescript for my project. Interestingly, when I execute 'vite dev', the live version of the website works flawlessly without any errors showing up on the console. However, things take ...

Tips for extracting key values from an array of objects in Typescript

I am working with an array called studyTypes: const studyTypes = [ { value: "ENG", label: "ENG-RU", }, { value: "RU", label: "RU-ENG", }, ]; Additionally, I have a state variable set ...

Restrict the parameter type using a type predicate

How can I effectively narrow types based on the value of a single field in TypeScript? It seems that using type predicates may not be working as expected to narrow down the types of other parameters within a type. Is there a way to ensure correct type na ...

My type is slipping away with Typescript and text conversion to lowercase

Here is a simplified version of the issue I'm facing: const demo = { aaa: 'aaa', bbb: 'bbb', } const input = 'AAA' console.log(demo[input.toLowerCase()]) Playground While plain JS works fine by converting &apo ...

Finding solutions using a controller class

I have a component that uses a controller class and accepts an input parameter through the use of a bindings object. In the controller, I am able to access the parameter after the constructor runs, but I cannot pass it as a constructor parameter. While wo ...

"Setting up a schema in TypeORM when connecting to an Oracle database: A step-by-step guide

As a newcomer to TypeORM, I'm using Oracle DB with Node.js in the backend. Successfully connecting the database with TypeORM using createConnection(), but struggling to specify the schema during connection creation. One workaround is adding the schem ...

How can we reduce the size of a JSON object in Typescript before sending it to the client?

Currently, I am faced with a common challenge. I have a database object that is a standard JS object originating from a document database, and my goal is to transmit this object to the client. However, certain fields contain sensitive information that shou ...

Typescript: How can we determine the data type of React Router Link?

Trying to pass Link from react-router-dom as props and needing to specify it in the interface. While hovering over the Link element, the type displayed is: React.ForwardRefExoticComponent<LinkProps & React.RefAttributes<HTMLAnchorElement>> ...

Angular 2 forms are displaying ngvalid when input fields are marked as nginvalid

The form displays ngvalid because I have included the code like this: <form novalidate class="pop-form" (submit)="signUp()" #regForm="ngForm"> <div class="group"> <input type="text" [(ngModel)]="signUpData.name" [ngMode ...