Unit testing for changes in AngularJS $scope variables within the .then() function

I'm currently facing an issue with unit testing a function in my controller. The problem lies in making a $scope variable testable. I am assigning the variable within the .then() block of my controller and need to ensure it is set correctly when the .then block is executed.

This is the snippet of my controller code:

function submit() {
    myService.submit().then(function(responseData){
        if(!responseData.errors) {
            $scope.complete = true;
            $scope.details = [
                {
                    value: $scope.formattedCurrentDate
                },
                {
                    value: "$" + $scope.premium.toFixed(2)
                },  
            ];
        } else {
            $scope.submitError = true;
        }
    });
}

The specifics of where this service call leads are not important. It will return JSON with

action: 'submitted', 'response' : 'some response'
. The .then() method checks for errors in the responseData, and if none are found, it should set certain details. I am attempting to test these $scope.details in my unit test below:

it('should handle submit details', function () {
    var result;
    var premium = 123.45;
    var formattedCurrentDate = "2016-01-04";
    var promise = myService.submit();
    mockResponse = {
        action: 'submitted',
        response: 'some response'
    };
    var mockDetails = [
        {
            value: formattedCurrentDate
        },
        {
            value: "$"+ premium.toFixed(2)
        }   
    ];

    //Resolve the promise and store results
    promise.then(function(res) {
        result = res;
    });
    //Apply scope changes
    $scope.$apply();
    expect(mockDetails).toEqual(submitController.details);
}); 

Now, I am encountering an error stating that $scope.details is undefined. I am unsure how to make the test recognize the change in $scope data within the controller.

In the beforeEach section and other functions in my unit test:

function mockPromise() {
    return {
        then: function(callback) {
            if (callback) {
                callback(mockResponse);
            }
        }
    }
}

beforeEach(function() {
    mockResponse = {};
    module('myApp');

    module(function($provide) {
        $provide.service('myService', function() {
            this.submit = jasmine.createSpy('submit').and.callFake(mockPromise);
        });
    });

    inject(function($injector) {
        $q = $injector.get('$q');
        $controller = $injector.get('$controller');
        $scope = $injector.get('$rootScope');
        myService = $injector.get('myService');

        submitController = $controller('myController', { $scope: $scope, $q : $q, myService: myService});
    });
});

What steps can I take to resolve the promise within my unit test so that I can use $scope.$digest() to observe the changes in the $scope variable?

Answer №1

If you're interested in testing promises with jasmine, check out this helpful resource:

Utilizing a callFake can help you mock the behavior you desire.

spyOn(myService, 'submit').and.callFake(function() {
  return {
    then: function(callback) { return callback(yourMock); }
  };
});

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

Incorporate a JavaScript variable within the src attribute of a script tag

Embedding Google's script allows for displaying a trends Map on our website. <script type="text/javascript" src="//www.google.com.pk/trends/embed.js?hl=en-US&q=iphone&cmpt=q&content=1&cid=TIMESERIES_GRAPH_0&export=5&w=500&a ...

How come the parameters in my function are being displayed as boolean values in JSDocs when that is not the intended behavior?

I am documenting my journey of following the React tutorial for tic-tac-toe, and I'm puzzled as to why the parameters of my function are showing up as boolean values in JSDocs when they are not supposed to. When I hover over the function with my curs ...

Hiding a div with Javascript when the Excel dialog box is loaded

I have a piece of JavaScript code that is activated when the user clicks on an excel image. $("#excel").on("click", function () { $('#revealSpinningWheel').reveal(); $(window).load(function () { $('#revealSpinningWheel').hide ...

Unable to utilize material tabs in this situation

Discovering the material tabs feature at https://material.angular.io/components/tabs/api#MatTab got me excited to implement it in my project. After adding the suggested import, I encountered an issue where I couldn't find the module "@angular/materia ...

Erase a set of characters with the press of the backspace key (JavaScript)

Within my textarea, I have lines that start with a number and a period: <textarea autoFocus id="text-area"wrap="hard" defaultValue ={this.state.textAreaVal} onKeyUp={this._editTextArea}/> For example: Line 1 Line 2 Line 3 I've created a ...

Tips for retrieving the location of a draggable waypoint in the Google Directions output

<!DOCTYPE html> <html> <head> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Location Partner</title> <!--styles for ...

JavaScript powered caller ID for web applications

I am currently working on an innovative project where I aim to automatically detect the phone number of a landline call to a specific device. While research led me to various packages like npm caller-id-node that work with desktop applications using the mo ...

How to align scrolling images with their scroll origin - a step by step guide

Curious to know the name of the effect where images scroll in a different orientation than the page, creating a 2D appearance. Take a look at the Google Nexus website and scroll down - do you see the effect? What is this effect called? Is it created usin ...

Whenever the state of a React component is modified, it does not automatically trigger a re

Currently, I am utilizing the React Infinite Scroller library to display a list of posts. Interestingly, my load more results function seems to be triggered three times, resulting in the update occurring thrice (verified through console.log). For renderi ...

I am trying to locate the source of the unexpected token error

Hi there! I've encountered a syntax error in my code, specifically pointing to the closing curly bracket right above the render method. The error message indicates that it's expecting a comma, but all my curly brackets seem to have opening and cl ...

What is the best method for transforming a stream into a file with AngularJS?

Currently, I have a server returning a file stream (StreamingOutput). My goal is to convert this file stream into an actual file using AngularJS, javascript, JQuery, or any other relevant libraries. I am looking to display the file in a <div> or ano ...

Exploring how Node.js, Express.js, and Mongoose work together to handle

I am experiencing difficulties with handling data received from APIs, as it returns null and doesn't wait even though I have used async/await functions. My goal is to retrieve data from the first URL, then gather data from other URLs based on the res ...

Rotating and scaling an image simultaneously using CSS3

I am feeling very puzzled. Why am I unable to simultaneously scale and rotate? Despite my attempts, it seems to be not working: .rotate-img{ -webkit-transform:scale(2,2); -webkit-transform:rotate(90deg); margin-left:20%; margin-top:10%; } ...

What makes React.js such a challenging skill to master?

Why am I struggling? After dedicating 6 months to learning React.js, I find myself overwhelmed by the multitude of chapters and feeling lost. Could you kindly share your journey with React.js in a step-by-step manner? Your advice would be greatly apprecia ...

Merging two arrays to create a JSON object

column_names: [ "School Year Ending", "Total Students", "American Indian/Alaskan Native: Total", "American Indian/Alaskan Native: Male", "American Indian/Alaskan Native: Female", "Asian/Pacific Islander: Total", "Asian/Pacific I ...

Troubleshooting Problem with Padding in ion-content for Ionic Angular

I am currently developing my inaugural Ionic application. The initial template I utilized was the rudimentary sidemenu layout. $ ionic start myApp sidemenu Afterwards, I crafted a straightforward page featuring a list which appears as follows... <ion ...

I am currently in the process of cross-referencing the tags that have been retrieved with those that have been selected or created. If a tag does not exist

I have a collection of tags in an object, and I want to dynamically add new tags before submitting the form. Despite using vue watch, it doesn't seem to be working for me. Here is the code snippet: data() { return { blog: { blog_ti ...

Utilizing jQuery for interacting with iframes

My script functions perfectly on the page, but when I embed it using an iframe, the jQuery features stop working even though the script is written as usual. Even using $.noConflict(); does not resolve the issue. ...

Strategies for Dealing with 'No Search Results' in Your Search Functionality

I am currently facing an issue with displaying "No Results Found" when a user utilizes my search feature. The current problem is that "No Results Found" appears immediately on the screen and then disappears while a search query is being processed, only to ...

Combining video.js and vue.js for seamless integration

Can anyone guide me on how to display a youtube video using a video.js player within vue.js? I'm new to integrations and not sure what it entails. Any assistance will be greatly appreciated. ...