AngularJS: $digest must be run before calling $httpBackend.flush()

I'm struggling to understand why I have to use $rootScope.$digest() before my test can pass with $httpBackend.flush().

If I skip it, I end up with

Error: No pending request to flush!

This is the code for my test:

it('should post a new task to the server', function() {

    $httpBackend.when('POST', $rootScope.serverRoot + '/task/create').respond({});

    var created = false;

    mockBoardService.addTask({name: 'Add dynamic categories'})
        .then(function(response) {
            created = true;
        }
    );

    $rootScope.$digest();

    $httpBackend.flush();

    expect(created).toBe(true);
})

The service function being called is:

this.addTask = function(data) {
    return $http.post($rootScope.serverRoot + '/task/create', data);            
}

I'm wondering about the necessity of using $rootScope.$digest.

Answer №1

mockBoardService.addTask is performing some asynchronous operations, causing issues when trying to flush() $httpBackend requests without $digest allowing the time for async tasks to complete. To handle this correctly with Jasmine 2.0 (slightly different in 1.3), a solution would look like:

it('should send a new task to the server', function(done) {

    $httpBackend.when('POST', $rootScope.serverRoot + '/task/create').respond({});

    var taskCreated = false;

    mockBoardService.addTask({name: 'Add dynamic categories'})
        .then(function(response) {
            taskCreated = true;
            done();
        }
    );

    $httpBackend.flush();

    expect(taskCreated).toBe(true);
})

Note the use of 'done' passed into the 'it' function.

For more information on asynchronous support in Jasmine, refer to

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

Looking to update this jQuery pop-up menu script to be compatible with Ajax functionality

I came across this script at The issue arises when the script is called multiple times, resulting in a cascade of pop-outs within pop-outs. I am currently exploring ways to prevent the execution of the script if the pop-out has already been set. Below is ...

JavaScript Issue: Unable to Update or Delete Table Row Data

Presently, I am involved in developing a project titled : Tennis Club Management using a blend of Javascript, HTML, CSS, and Bootstrap. This project encompasses several HTML pages and a JS file such as index.html, profile.html, manageFees.html, index.js, e ...

Replace the identifier with the corresponding ID if it aligns with another ID when using Node.js or JavaScript

const info = [ { system: { id: "4gSSbjCFEorYXqrgDIP2FA", type: "Entry", content: { type: { name: "Writer" } }, }, InfoDetails: { shortSlugOption: { "en-us": "some value", "za-op": "random value" }, mediaFileAsset ...

What is the best way to switch between two components using vue.js?

I have a scenario where I need to toggle between two components, Register.vue [`my_reg-page`] and Login.vue [`my-signin_page`]. If the user opens the register page in the browser (using the /register URL), clicking on the Login heading will toggle the user ...

Is there a way to disable the backspace keycode in an input field?

I need to disable all keys in input field, this is what I have so far window.onkeypress = function(event) { event.preventDefault(); if (event.charCode && (event.charCode < 48 || event.charCode > 57)) { return false; } } <input type="t ...

Encountering an unexpected token error while attempting to incorporate JQuery into a React JS project

I am currently diving into the world of React.js and attempting to incorporate a side navigation bar on my homepage. However, I encountered an eslint error when trying to implement the sidebar using jQuery code. Below you will find the code snippet for the ...

Develop a plugin architecture using JavaScript and Node.js

Here is a basic implementation using node.js with express: var express = require('express'); var app = express(); app.get('/', function(req, res){ res.send('Hello World'); }); app.listen(3000); I am interested in creatin ...

Transmit analytical data to an external domain without expecting a reply

Initial Conditions I have ownership of mysite.com I lack ownership of othersite.com, but I am able to embed javascript code on that site Query What is the method to transmit analytic data from othersite.com to mysite.com ? ...

Tips on sending parameters from a PHP script to a Javascript file

I am struggling with my new journey into the world of JavaScript. I have been attempting to pass a parameter from a PHP file to a JavaScript file, but for some reason, it's just not working. Here's the code snippet: The JavaScript file is named ...

Retrieving an image URL from JSON information

I am currently working on a project where I need to fetch data from a PHP file that retrieves information from a database table. The specific result I am looking for is the 'pageLocation' of a single record from the 'page' table. This d ...

Updating the state across various components proves to be a challenge when relying on both the context API and higher order components

I have been working on updating the application state using the context API instead of using Redux, as I do not require all of its features and want to avoid prop drilling. With TypeScript, I created a global context and a higher-order component (HOC) wrap ...

Guide to selecting multiple rows at once using ng-options in a list

Need assistance with an HTML list: I have a box displaying a list where users can select multiple items to save. The saving and retrieving process is functional as the selectedList stores the user's previous selections, while fullList contains all av ...

Is there a way to incorporate an SSL certificate into a JavaScript POST request?

I need to send a post request to an endpoint using a SSL certificate in either typescript or javascript. This is for a project that I am currently working on with Ionic 3. ...

How do I repeatedly invoke a function in JQuery that accepts two different arguments each time?

I have a collection of folders, each containing various images. The number of pictures in each folder ranges from 8 to 200. Folders are numbered from 1 to 20 and the images within them are also labeled numerically. My goal is to aggregate all these images ...

What is the purpose of creating redirects instead of just "processing" data?

Upon pressing the subscribe button, a form is submitted. Previously, I used axios. The POST request is sent to https://api.skymongoose.com/subscription. Why does it redirect to a blank page even though the URL points to https://api.skymongoose.com/subscri ...

Utilizing X-editable in an ASP MVC View: navigating the form POST action to the controller

I have been utilizing the X-Editable Plugin to collect user input and perform server submissions. However, I am encountering an error during submission. What adjustments should I make in order to ensure that the x-editable data functions properly with the ...

There appears to be an issue where the session object cannot be retrieved by the Struts2 action

I have a struts2 action that is invoked by a JavaScript function. The JavaScript function uses uploadify to enable multiple file uploads: <script type="text/javascript"> $(document).ready(function() { $("#fileupload").uploadify({ ...

The search engine results page (SERP) is only displaying the homepage and not any of the subpages

Check out this search to see that only my main page is indexed. Why aren't Google and other search engines picking up arda-maps.org/about/ and the other subpages? Is my deep linking technique incorrect? Do the search engines just need more time? If s ...

The CycleDOM conundrum with conditional rendering

Having a problem with conditional rendering. Check out my flawless view: function todoItem(todo) { return li('.list-item',[ todo.editing ? input('.todo-edit', {type: 'text', value: todo.text, autofocus: true, attributes ...

Can Angular's built-in internationalization features be used to translate bindings?

Challenge The task at hand involves integrating translations into an Angular 6 application to support static text in multiple languages. The objective is to have the ability to choose a language during the build process without requiring dynamic translati ...