Anticipated that the absence of a value would match the presence of an Object

Struggling with running AngularJS unit tests for $resource using Jasmine v2.0 and Karma v0.13, I managed to convert custom actions to newer syntax successfully. However, a specific type of test is giving me trouble, which I suspect is related to $httpBackend. When testing this line, the following failure occurs:

Expected null({  }) to equal Object({  }).

The issue lies in the latest expectation in my actual test code:

      // ---
      callback = jasmine.createSpy();
      // ---

      it("should create resource", function() {
        $httpBackend.expect('POST', '/CreditCard', '{"name":"misko"}').respond({id: 123, name: 'misko'});

        var cc = CreditCard.save({name: 'misko'}, callback);
        expect(cc).toEqualData({name: 'misko'});
        expect(callback).not.toHaveBeenCalled();

        $httpBackend.flush();
        expect(cc).toEqualData({id: 123, name: 'misko'});
        expect(callback).toHaveBeenCalledOnce();
        expect(callback.calls.mostRecent().args[0]).toEqual(cc);
        expect(callback.calls.mostRecent().args[1]()).toEqual({});
      });

UPDATE

Resolved the issue.
It appears that the problem stems from how Angular creates an empty object when comparing with null and {}. The newest versions of Jasmine seem to struggle with this comparison method.

/**
 * Creates a new object without a prototype. This object is useful for lookup without having to
 * guard against prototypically inherited properties via hasOwnProperty.
 *
 * Related micro-benchmarks:
 * - http://jsperf.com/object-create2
 * - http://jsperf.com/proto-map-lookup/2
 * - http://jsperf.com/for-in-vs-object-keys2
 *
 * @returns {Object}
 */
function createMap() {
  return Object.create(null);
}

Answer №1

Upon inspecting the AngularJS source code, I discovered that there are instances where objects are constructed using Object.create(null), as shown in the example below.

/**
 * This function creates a new object with no prototype. Such an object proves to be beneficial for efficient lookup operations without having to worry about inherited properties from prototypes.
 *
 * Additional performance benchmarks:
 * - http://jsperf.com/object-create2
 * - http://jsperf.com/proto-map-lookup/2
 * - http://jsperf.com/for-in-vs-object-keys2
 *
 * @returns {Object}
 */
function createMap() {
  return Object.create(null);
}

I noticed that Jasmine 2.0 introduced support for comparing prototype types, causing some expectations to fail.

To remedy this, tests can now be structured like so:

expect(callback.calls.mostRecent().args[1]()).toEqual(Object.create(null));
, which should result in a successful test outcome.

Answer №2

I believe there might be an extra () in your code. Make the following adjustment;

expect(callback.mostRecentCall.args[1]()).toEqual({});

to

expect(callback.mostRecentCall.args[1]).toEqual({});

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

Does writing JavaScript code that is easier to understand make it run slower?

While browsing the web, I stumbled upon this neat JavaScript program (found on Khan Academy) created by another user: /*vars*/ frameRate(0); var Sz=100; var particles=1000; scale(400/Sz); var points=[[floor(Sz/2),floor(Sz/2),false]]; for(var i=0;i<part ...

Switching to http2 with create-react-app: step-by-step guide

Can someone provide guidance on implementing http2 in the 'create-react-app' development environment? I've searched through the README and did a quick Google search but couldn't find any information. Your assistance is much appreciated. ...

Error: No @Directive annotation was found on the ChartComponent for Highcharts in Angular 2

I'm having trouble integrating Highcharts for Angular 2 into my project. After adding the CHART_DIRECTIVES to the directives array in @Component, I encountered the following error in my browser console: EXCEPTION: Error: Uncaught (in promise): No ...

Performing AJAX callback function on success in jQuery

I've been trying to troubleshoot an error but none of the solutions I've found so far seem to be working for me. I have an ajax request set up to retrieve JSON data from the server. I can see the JSON data that I want to capture when using consol ...

Learn how to build a table using JSON data in conjunction with angularJS and PHP backend for your web

Currently, I am working on a project that involves PHP backend and AngularJS. In the login.php file, there is a query which returns a result saved in variable $result. This result is then passed to app.JS where it is stored in a cookie and displayed in the ...

JavaScript innerHTML not functioning properly when receiving a response from a servlet

Can someone help me troubleshoot the code below? I'm receiving a response from the servlet, but I can't seem to display it inside the div. Here is the response: lukas requests to be your friend &nbsp <button value="lukas"onclick="accfr(th ...

Unable to load the .js file within the Angular module

I am facing an issue with my Angular sidebar component that is trying to load a local script called sidebar.js. I have the following code in src\app\sidebar\sidebar.component.ts: ngAfterViewInit(): void { const s = document.createEleme ...

Transform an array of arrays object with multiple depths into an array of objects

Having some difficulty with the conversion of an array of arrays-like object into an array of objects. The reduce method is being used, and it successfully converts the array data to an object for the first set of arrays. However, on the second iteration, ...

Displaying a page using express.Router()

I'm having trouble figuring out how to incorporate EJS rendering into a file utilizing express.Router(). The usual method of router.set('view engine', 'ejs') doesn't seem applicable in this context. Any ideas on how I can succ ...

Issues with removing options from Autocomplete persist in React MaterialUI

Currently navigating the world of ReactJS and experimenting with Material UI's Autocomplete component. The challenge lies in managing a complex data structure where options are dynamically generated based on user selections, but removing previously se ...

`Need help testing flow.js file uploads using Selenium?`

My AngularJS SPA allows users to upload files using the ng-flow wrapper for flow.js. I am currently in the process of setting up automated e2e tests with Selenium, but I am facing challenges when it comes to testing the file uploading mechanism triggered b ...

Leverage JSON files for pagination in NextJS

I am currently developing a science website where the post URLs are stored in a static JSON file. ScienceTopics.json- [ { "Subject": "Mathematics", "chapters": "mathematics", "contentList": [ ...

Deleting database information using Jquery when a div is clicked

I'm looking to create an alert system where users will see a pop-up alert on their screen. However, I am facing a major issue in removing the div completely. I understand that I need to remove it from the database, but I'm struggling with finding ...

Troubleshooting Vue and Laravel API CRUD: Issue with updating data

I am currently working on building a simple CRUD application using Laravel 9 and Vue js 3. However, I have encountered an issue where the method does not seem to be functioning correctly. The update method from the Laravel API works perfectly fine (I test ...

Error in mandatory data required by the Screenleap API in JavaScript

I have a JSON encoded data stored in a variable called $json. Here is how it appears: I have referred to the documentation at "https://www.screenleap.com/api/presenter" ...

Updating NodeJs to Express 4.0 may result in encountering errors

Hey there, I've been diving into node.JS and the express module recently and came across this helpful resource link However, when attempting to update the dependencies to express 4.0 in the example provided, it seems to break. I understand that app.c ...

Upon transitioning from typescript to javascript

I attempted to clarify my confusion about TypeScript, but I'm still struggling to explain it well. From my understanding, TypeScript is a strict syntactical superset of JavaScript that enhances our code by allowing us to use different types to define ...

Unable to retrieve data in Node Express after querying completion

I created a basic custom module that is intended to return database records from its methods. After executing a query, I can retrieve all the records but when attempting to assign them to a variable, it shows as null. I'm unsure of what's causin ...

The encodeURIComponent function does not provide an encoded URI as an output

Looking to develop a bookmarklet that adds the current page's URL to a specific pre-set URL. javascript:(function(){location.href='example.com/u='+encodeURIComponent(location.href)}()); Even though when I double encode the returned URL usin ...

Error Code 18: Unable to Open Database - Troubleshooting in AngularJS and Cordova

Looking to set up an SQLite database using Angular.js and Cordova without relying on Ionic? Check out the following steps for initializing your app. $(function() { new AppInitializer(); }); var AppInitializer = function() { // Determine platform - we ...