The step-by-step guide to testing an Angular promise using Jasmine

An issue arises when attempting to test the code below using Jasmine, as the console.log in `then` is never called. The question remains: is this problem related to Angular or Jasmine?

describe("angular test", function() {

        var $q;

        beforeEach(function() {
          angular.mock.inject(function getDependencies(_$q_) {
            $q = _$q_;
          });
        });

        it("angular nested promise with jasmine", function(done) {

          $q(function(resolve, reject) {
              resolve(10);
            })
            .then(function(r) {
              console.log(r);
            })
            .finally(function() {
              done();
            });
        });
      })
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/jasmine/2.3.3/jasmine.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jasmine/2.3.3/jasmine.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jasmine/2.3.3/jasmine-html.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jasmine/2.3.3/boot.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js"></script>
<script src="https://code.angularjs.org/1.4.5/angular-mocks.js"></script>

Special thanks to Merott for providing the solution.

Next inquiry:

When testing a service that returns a promise which is wrapped within the service, including a digest is necessary. But, is the digest required solely for Jasmine or even in usual cases (meaning for the service)?

Answer №1

To initiate the digestion process, you need to include $rootScope and execute $rootScope.$digest().

describe("Angular Testing", function() {

  var $q, $rootScope;

  beforeEach(function() {
    angular.mock.inject(function loadDependencies(_$q_, _$rootScope_) {
      $q = _$q_;
      $rootScope = _$rootScope_;
    });
  });

  it("Testing nested promises in Angular using Jasmine", function(done) {
    $q(function(resolve, reject) {
      console.log('hello');
      resolve(10);

    }).then(function(result) {
      console.log(result);
    }).finally(function() {
      done();
    });
    
    $rootScope.$digest();
  });
})
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/jasmine/2.3.3/jasmine.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jasmine/2.3.3/jasmine.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jasmine/2.3.3/jasmine-html.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jasmine/2.3.3/boot.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js"></script>
<script src="https://code.angularjs.org/1.4.5/angular-mocks.js"></script>

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

When I try to use Node.js and Express, I encounter an issue where I receive the

I recently developed a basic application. Everything was running smoothly until I decided to organize the code using an MVC template. However, now when you visit localhost:3000/add-service, you are greeted with a "Cannot Get /add-service" error message. W ...

Adding a property conditionally in jsx: A guide

I have a simple example of Material UI RadioGroup code that I want to display conditionally in either a row or column format. By default, it is displayed in column format. Below is the code snippet: <RadioGroup aria-label="gender" name=&q ...

Velocity.js causing a slowdown in animated performance

Currently, I am attempting to animate spans, and while the animation is functional, it appears to be somewhat choppy and lacks smoothness. https://codepen.io/pokepim/pen/JBRoay My assumption is that this is due to my use of left/right for animation purpos ...

Swap out the image for a div element if the image is not found

Is there a way to accurately display an image if it's available, and use a div as a replacement if the image is not present? // How can I determine `imageExists` without encountering cross-origin issues? (imageExists) ? (<img class="avatar-img" sr ...

JavaScript and HTML - specify the location in the html document where the JavaScript script will be displayed

I'm a beginner when it comes to JavaScript. I am trying to make sure that my HTML page remains unchanged while JavaScript text is displayed in a specific location without refreshing the entire page. To trigger a JavaScript function via a button on a ...

Modify an array by incorporating values from another array that have a matching property

I have two arrays that look like this let array1 = [{ 'id': 1, 'name': 'A' }, { 'id': 2, 'name': 'B' }, { 'id': 3, 'name': ' ...

Filtered Owl Carousel

Hello everyone. Just wanted to mention that our English may not be perfect. I managed to filter with owl carousel by tweaking some codes I found online. It's working now, but I'd love for it to have an animated effect while filtering, like a fad ...

How can you nest a map within a map in JavaScript?

Here is the code snippet I am working with: _renderChannels() { return this.state.channelsData.map(channelData => { return this.state.channelsStreamData.map(channelStreamData => { return <Channel channelData={channelData} ch ...

Introducing a Node JS web application unaccompanied by hosting services

As I prepare for a coding competition and want to display my computer's IP address, I am wondering if it is safe to type in my home computer's IP once I start serving the webapp before leaving my house. Apologies if this question seems silly. ...

Angular is attempting to access a function that has not been utilized within the return object of the directive

Below is the directive I am currently using: 'use strict'; angular.module('App') .directive('aView', function ($stateParams) { this.link = function(scope, template, directiveAttrs){ template.addClass(scope.elem.c ...

What is the best way to execute 2 statements concurrently in Angular 7?

My goal is to add a key rating inside the listing object. However, I am facing an issue where the rating key is not displaying on the console. I suspect that it might be due to the asynchronous nature of the call. Can someone help me identify what mistak ...

What is the best way to convert a JSON object back into an object with its own set of methods?

Currently, I have a JavaScript object with multiple methods attached via prototype. When I serialize the object to JSON, only the property values are saved, which is expected. It wouldn't make sense to save the methods as well. Upon deserialization ...

Utilizing SQLite in an AngularJS Application: A Comprehensive Guide

When attempting to use SQLite in AngularJS, I encountered an error stating: "Module name 'sqlite3' has not been loaded yet for context: _. Use require([]) - can anyone assist me with this issue? var sqlite3 = require('sqlite3').verbos ...

Is there a way to retrieve the default ObjectId generated by MongoDB when using NextAuth?

Is it possible to access the MongoDB ObjectId of the user currently logged in when using Next Auth with services like Twitter? When signing in, Next Auth creates a new user, account, and session, but I'm unable to retrieve the _id value for my server ...

Tips for resolving the 'node-gyp rebuild' problem on Windows 10

While attempting to incorporate a node NPM dependency into my project, I encountered an issue with node-gyp rebuild, which I have already reported. I am aware of a potential solution from this Stack Overflow post, but unfortunately it is not effective for ...

The CSS styles are functioning correctly in index.html, but they are not applying properly in the component.html

When the UI Element is clicked, it should add the class "open" to the list item (li), causing it to open in a collapsed state. However, this functionality does not seem to be working in the xxx.component.html file. Screenshot [] ...

Query modifier contains an unexpected token ":"

For my API project, I have opted to use sailsjs as my framework. The documentation at provides a list of query modifiers that can be used. User.find({ or: [ name: { startsWith: 'thelas' }, email: { startsWith: 'thelas' } ] ...

What is the process of generating a dynamic card/button element on an ASP.net webpage using information from the backend database?

I'm faced with a challenge of displaying employees' names and titles from a MSSQL Server database table on an ASP .NET webform as individual "card" objects. Currently, I am able to showcase a static number of records by using an asp button object ...

Can one extract the content from a secure message received from a Telegram bot?

Currently, I am utilizing the sendMessage() function with protected_content: true in order to prevent Telegram users from forwarding my bot's messages to others. Prior to implementing this setting, the text below was easily copyable. However, after e ...

Refine object array by applying multiple filters based on various values

Currently, I have an array of objects that I need to filter based on user input. For example, if a user enters "Red Shirt," I want to only return entries with values like {color: "red", clothingType: "shirt"} rather than {color: "red", clothingType: "scar ...