A frigid commitment sealed within a software test

I've encountered an unexpected issue while testing a service that returns a standard $q promise. Strangely, none of the promises I test seem to be resolved or rejected (specifically, the handlers from then are not being called even though the code inside the promise runs without any problems). I've attempted to force a digest on the root scope as suggested in some answers on SO, but to no avail.

Below is a concise example demonstrating the issue:

describe('promise', function(){
  jasmine.DEFAULT_TIMEOUT_INTERVAL = 500;
  let q;

  beforeEach(inject(function($q){
    q = $q;
  }));

  it('finishes', function(done){
    expect(q).toBeDefined();
    const promise = q.resolve();
    console.log(promise);
    promise.then(
      () => done(),
      () => done.fail()
    );
  });
});

What steps should I take to ensure the promise behaves as expected?

Answer №1

This particular instance is designed to assist you in comprehending the functionality of $rootScope.$digest() (even if you have previously experimented with forcing a digest). Please disregard the type declarations provided, as they were initially scripted using TypeScript.

    var service: IService;
    var $rootScope: ng.IRootScopeService;
    var $q: ng.IQService;

    beforeEach(() => {
        angular.mock.module("app");
        angular.mock.inject((
            _$rootScope_: ng.IRootScopeService,
            _$q_: ng.IQService
        ) => {
            // Implement dependencies 
            $q = _$q_;
            $rootScope = _$rootScope_;
        });

        // Set up service
        service = new Service($q);
    });


    it("should call errorCallback", () => {
        let callback = {
            errorCallback: function (response: any) { /*empty function */ }
        };

        spyOn(callback, "errorCallback");

        service.connect(null)
            .catch(callback.errorCallback);

        // Execute a digest on rootScope (essential for $q implementation) 
        $rootScope.$digest();

        expect(callback.errorCallback).toHaveBeenCalled();
    });

Answer №2

To ensure proper execution, it is important to include $scope.$apply() (or $rootScope.$digest()) and define then() before calling it as shown in the modified example below:

describe('promise', function(){
  jasmine.DEFAULT_TIMEOUT_INTERVAL = 500;
  let q;
  let scope;

  beforeEach(inject(function($q, $rootScope){
    q = $q;
    scope = $rootScope.$new();
  }));

  it('finishes', function(done){
    expect(q).toBeDefined();
    const promise = q.resolve();
    promise.then(
      () => done(),
      () => done.fail()
    );
    scope.$apply();
  });
});

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

Organizing an array based on designated keywords or strings

Currently, I am in the process of organizing my logframe and need to arrange my array as follows: Impact Outcomes Output Activities Here is the initial configuration of my array: { id: 15, parentId: 18, type: OUTPUT, sequence: 1 }, { id: 16, parentId: ...

The dynamic scope variable in AngularJS is failing to update after a successful HTTP POST request

Struggling with retrieving data from a database and assigning it to a dynamic scope variable using a function. The issue lies in the fact that the data is not being assigned to the variable on the first attempt. Can anyone offer assistance? Here's th ...

Passing arguments from an Angular directive to a controller function within an element's HTML

Is there a way to pass the URL of an anchor tag in the directive to the controller function "itemClicked"? The code below successfully logs the "post" object when clicked. HTML: <div ng-repeat="post in posts" > <div find-urls link-clicked="i ...

Freezing the website by setting async to false

I've been having issues with my website freezing when using async set to false. I need confirmation before executing the script. $.ajax({ type: "POST", url: url, data: form.serialize(), async: false, success: function(data) { ...

Enhancing Rails functionality with drag-and-drop to modify object attributes

I work with two main models: Collections and Images Collection Model class Collection < ActiveRecord::Base has_many :images, dependent: :destroy accepts_nested_attributes_for :images end Image Model class Image < ActiveRecord::Base belongs_ ...

What is the best way to transfer the data from one JavaScript object to a new, empty object?

My Angular site requires a JavaScript object (JSON retrieved from a database) to display widgets: [{'widget_id':'1','widget_name':'Blue Widget','widget_description':'A nice blue widget','wid ...

Make a JavaScript request for a page relative to the current page, treating the current page

When accessing the page /document/1, the request $.getJSON('./json', ... is sending a request to /document/json I'm interested in requesting /document/1/json Is there a method available to automatically resolve this path without having to ...

The time that was constructed is not a valid function

I am currently working on a puppeteer script that interacts with my browser extensions and navigates to a specific page. It clicks on a particular extension button and fills in an input. Unfortunately, I am encountering an issue with the following error me ...

Having two ng-click events and two distinct classes in an ng-repeat based on the selected option

There are two buttons in my code that should remove a div within an ng-repeat loop. Depending on which button is clicked, a custom CSS class should be added to the effect. The CSS changes based on the option selected. When I click on a button, either &apo ...

Tips for properly handling special characters in DOM elements

I'm encountering an issue while trying to set CSS based on a condition inside quotes. This is causing a syntax error for me. Can anyone provide assistance in finding a solution? <div> <span ng-class='{\' rdng-error-rate&bsol ...

Issue with fuse-box: unable to import ReactDOM

Recently, I decided to switch from webpack to fuse-box for my side project. Everything is compiling without any issues, but when I try to load it, an error pops up: I downloaded a React demo code and it works fine. Additionally, there are no problems wit ...

No results found by Mongoose find() method

I've set up a route that utilizes a model named Todo as shown below: app.get('/api/todos', function(req, res) { Todo.find({},function(err, todos) { if (err) res.send(err); console.log("number of todos " + tod ...

Remove inline CSS from HTML elements

Having a large HTML file structured like this: <div style="min-height: 32px; padding: 5px; width: 800px; margin: 50px auto; overflow: auto; font-size: 12px;" class="selectable clearfix selected_layer" id="wrap"> <div class="selectable" id="l1" st ...

The functionality of React-router-dom protected routes seems to be malfunctioning

Understanding Protected Routes in React.js: While looking at the implementation of protected routes, you may notice that 'false' is being directly used in the if statement. However, even with this condition, the page is still accessible. Why doe ...

Transmit an unmodifiable array using JSON and Ajax

Is there a way to transmit arrays in a non-editable format? The data I wish to transmit looks like this: var items = []; //console.log(JSON.stringify(items)); allitems = JSON.stringify(items); [{ "assetid": "7814010469", "classid": "1797256701", ...

Rdash Angular: How to Implement a Fixed Header Position on Page Scroll

Hi there, I am currently utilizing Rdash Angular Js. I am wondering if it's achievable to keep the header position fixed while scrolling through the page. I attempted a solution using CSS as shown below, unfortunately it didn't have the desired ...

Tips for creating a highly adaptable code base- Utilize variables

Can anyone help me optimize this lengthy and cumbersome code in HTML and JS? I want to make it more efficient by using variables instead of repeating the same code over and over. In the HTML, I've used href links to switch between different months, w ...

Error: JSONP Label Validation Failed

My JSON URL is: The above URL returns the following JSON: { token: "2cd3e37b-5d61-4070-96d5-3dfce0d0acd9%a00a5e34-b017-4899-8171-299781c48c72" } Edit: Changed it to {"token": "2cd3e37b-5d61-4070-96d5-3dfce0d0acd9%a00a5e34-b017-4899-8171-299781c48c72"} ...

Error: Unable to access 'createInvite' property from undefined variable

Having trouble generating an invite to one of my guild's channels. Here is the code snippet I am using: const { Client } = require("discord.js"); const client = new Client({ intents: [] }); client.on("ready", async () => { ...

Utilizing an AngularJS custom filter twice

Experimenting with a custom Angular filter example found at: https://scotch.io/tutorials/building-custom-angularjs-filters#filters-that-actually-filter, my version looks like this: <!DOCTYPE html> <html> <script src="http://ajax.googleapi ...