Testing a promise with Jasmine unit testing through mocking

I'm struggling with testing my promise unit test.

An assertion "expect(scope.test).toBe(12);" has been added to the promise then block in my code.

Here is the snippet of code I am attempting to test:

$scope.getBudgets = function(){
    BudgetService.getBudgets().then(function(response) {
        $scope.test = 12;

    }, function(response) {

    });
}

Below is the unit test I have written:

describe('budgetOverviewCtrl tests', function() {

beforeEach(module('app'));
beforeEach(module('ngRoute'));

var ctrl, scope, deferred;

describe('budgetOverviewCtrl with test', function() {
    beforeEach(inject(function($controller, _$rootScope_) {

        scope = _$rootScope_.$new();

        ctrl = $controller('budgetOverviewCtrl', {
            $scope: scope
        });         
    }));

    it('Should verify if getBudgets service promise exists and returns as expected', inject(function($injector, $q, BudgetService) { 

        BudgetService = $injector.get("BudgetService");         

        deferred = $q.defer();
        deferred.resolve({"Hello": "World"});   

        spyOn(BudgetService, 'getBudgets').and.callFake(function() {
            return deferred.promise;
        }); 

        scope.getBudgets();

        expect(BudgetService.getBudgets).toHaveBeenCalled();

        **//The following line is within the promise then block.**
        expect(scope.test).toBe(12);
    }));
});
});

Answer №1

Make sure to include $rootScope.$apply() immediately following the invocation of scope.getBudgets() within your test code. In Angular, promise callbacks are executed within the digest cycle and need to be manually triggered during testing scenarios.

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

Is it possible to switch states in Angular UI Router without altering the URL?

The feature of multiple nested views in the ui-router is quite convenient as it allows for seamless transitions between different states within an application. Sometimes, there may be a need to modify the URL while navigating through states, while at othe ...

Tips for showing legend symbols within tooltips on Highcharts

I've encountered an issue with Highcharts that I need help with. In my Highcharts chart, I'm trying to transfer the symbol from the legend to the tooltip. I'm tackling this challenge in two scenarios: Lines: I have two series, one with a ...

Error handling in Angular is not properly managing the custom exception being thrown

I am currently working on an Angular 12 application and I have a requirement to implement a custom ErrorHandler for handling errors globally. When I receive an error notification from the backend, I subscribe to it in the ToolService using this.notificati ...

Rendering issue with component

I am encountered with a situation where one component is failing to render its sub-component. Surprisingly, there are no visible errors in the console. The data I'm expecting from the web call is also coming through without any issues. However, for so ...

Event handling in Asp.net dropdownlist when the selected index is changed

I am facing an issue with the dynamic controls in my ASP.NET page. For example, I have created a TextBox dynamically with the following code: TextBox ratingtxtbox = new TextBox(); ratingtxtbox.ID = "Rating_1"; And also a DropDownList like this: DropDow ...

The multi-level navigation bar is not displaying properly

I am currently facing an issue with my Mega menu. It displays two levels of menus perfectly fine, but I need to add a third level as shown in the image below. However, when I try to include the third level, it disrupts the design and causes the Grand Child ...

What is the best way to set the input type in AngularJS based on a variable?

Is there a way to dynamically set the input type based on another variable in AngularJS? I was considering using a directive that triggers from an onclick event to change the input type, but I'm not entirely sure. FIRST //loop <a class="orgTitle" ...

How do I submit my form data as a JSON object using AngularJS?

I'm currently in the process of developing my first Angular app and trying to incorporate form submission into JSON data. Below is the form I have created: <span ng-show="show"> <form name="inputForm" class="form-group" ng-controller="For ...

Pager.js utilizing Deferred Bindings

I am currently working on using Pager.js to develop a single page application. The structure I have set up is as follows: #word/definition #word/example #word/synonym This means that definition, example, and other elements are divs with page bindings: & ...

"Explore the endless possibilities of Prototyp JavaScript with an array of innovative new features

I recently created a collection form using Symfony, consisting of a Mainform and Subforms within it. The functionality allows me to add new Mainforms and corresponding Subforms, which is working perfectly with my current script. However, the issue I&apos ...

w2ui failing to recognize input from HTML form

w2ui seems to be ignoring the input tag's value attribute. How can I make it use the specified value? It works fine with selects. https://i.sstatic.net/pNSey.png Check out the jsfiddle link for more information <div id="form" style="width: 750 ...

Guide to generating dynamic arrays in JavaScript when a button is clicked

I am working on a JavaScript program where I dynamically generate buttons and div tags, as well as retrieve data from a local JSON file. My goal is to implement a new feature where clicking a button will create an array with the same name as the button, al ...

Show unique language text in the <noscript> element based on the user's browser language

I am just starting out with HTML, and I would like to show a message if JavaScript is disabled. To do this, I have placed the message within the <noscript> tag, which is working perfectly. <noscript> Need to enable Javascript. </noscript> ...

The Radiobutton .val() function will always return a value, even if no radiobuttons have been selected

Within my form, I have 3 sets of radio buttons that are all properly labeled. When the user submits the form, I want to verify if they selected an option from each group. To achieve this, I have implemented the following method: $('.form').sub ...

Is there an equivalent function to onAdd in Material-UI when using MUI Chip?

In my exploration of the latest version of Material-UI, MUI, I observed that the "onAdd" property has been removed. The only function properties remaining are "onDelete" and "onClick". I am interested in generating new chips based on user-input tags. Is ...

Issue encountered while attempting to save the date to a json file

While working on my code to directly print the date from index.js into data.json, I encountered an error stating that data is not defined. This is what I have done so far: Ran npm init Installed jsonfile using npm i jsonfile index.js const json ...

What steps can I take to incorporate a user-controlled autoscroll feature into this Carousel?

I am in the process of creating a "slideshow" using text boxes that can be scrolled with arrow buttons. My goal is to have the slideshow automatically scroll only until the user interacts by clicking one of the arrow buttons. Below is the state logic re ...

Looking for an example of a Three.js AnimationClip

Trying to create simple keyframed animations in threeJS with an object3D for moving, rotating, and scaling? Check out this outdated example: . However, be warned that the animation rotation has switched to quaternion in threeJS. Struggling to find a strai ...

Tips for effectively monitoring scope for data loading

I have successfully created a custom Angular directive that utilizes D3.js to create a visualization. In my HTML, I reference this directive as follows: <gm-link-analysis data="linkAnalysis.connections"></gm-link-analysis> The relevant part o ...

After initiating the Stripe checkout process, the req.params and req.user variables seem to be absent

I am in the process of incorporating Stripe subscriptions billing into my application using a tiered pricing model. From what I understand, there are two key tasks that need to be completed: Enable new users to create a Stripe customer account through the ...