Detecting Unflushed Requests in Jasmine and AngularJS

I'm encountering some issues passing certain tests after implementing $httpBackend.verifyNoOustandingRequest().

Interestingly, excluding this from my afterEach function allows the tests to pass successfully. However, including it causes all tests to fail except for the last one 'should load items from the server'. Each failed test shows the response as 'Error: unflushed request: 1' except for the final test.

It's puzzling because I was under the impression that flushing is only necessary when mocking an Ajax request, yet it's causing failures in all tests except the actual server test.

Any assistance on this matter would be greatly appreciated.

describe('controller: ListCtrl', function(){
beforeEach(module('notesApp'));
var ctrl, loc, mockService, itemServiceS, mockBackend;
beforeEach(inject(function($controller, $location, ItemService, $httpBackend){
    spyOn(ItemService, 'list').and.returnValue([{id: 1, label: 'First', done: true}]);
    itemService = ItemService;
    mockBackend = $httpBackend;
    mockBackend.expectGET('/api/note').respond([{id: 1, label: 'Mock'}]);
    ctrl = $controller('ListCtrl');         
    loc = $location;
}));
it('Should have items available on load', function(){
    expect(ctrl.items).toEqual([
        {id: 1, label: 'First', done: true},
        {id: 2, label: 'Second', done: false}
    ]);
});
it('Should have highlight items based on state', function(){
    var item = {id: 1, label: 'First', done: true};
    var actualClass = ctrl.getDoneClass(item);
    expect(actualClass.finished).toBeTruthy();
    expect(actualClass.unfinished).toBeFalsy();

    item.done = false;
    actualClass = ctrl.getDoneClass(item);
    expect(actualClass.finished).toBeFalsy();
    expect(actualClass.unfinished).toBeTruthy()
});
it('should change the url', function(){
    expect(loc.path()).toEqual('');
    ctrl.navigate1();
    expect(loc.path()).toEqual('/some/where/else');
});

it('Should change the url to /some/where', function(){
    expect(loc.path()).toEqual('');
    ctrl.navigate2();
    expect(loc.path()).toEqual('/some/where');
});
it('Should have called through ItemService factory', function(){
    expect(itemService.list).toHaveBeenCalled();
    expect(itemService.list.calls.count()).toEqual(1);
    expect(ctrl.itemsGet).toEqual([{id: 1, label: 'First', done: true}]);

});
it('Should load items from server', function(){
    expect(ctrl.retrievedItems).toEqual([]);
    mockBackend.flush();
    expect(ctrl.retrievedItems.data).toEqual([{id: 1, label: 'Mock'}]);
});
afterEach(function(){
    mockBackend.verifyNoOutstandingExpectation();
    mockBackend.verifyNoOutstandingRequest();
})

});

Answer №1

Without visibility into your controller code, it is difficult to say for certain, but it appears that the mock API request is being initiated during controller initialization. This means the request will always be sent and must be cleared in order to meet the assertions in your afterEach block.

The expect() syntax of $httpBackend is rigid, so you might find using the when() syntax more beneficial as it offers a looser and "black box" approach. For more information on the variances between these two approaches, refer to the angularJS documentation for $httpBackend

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

connection and navigation hiccup

In my current project, I am utilizing Redux and React. Within App.js, I've implemented some Routes and also make use of the connect function from react-redux. In order to avoid any potential update blocking issues, I typically wrap my component in the ...

How to choose a javascript drop down using selenium?

Here is the HTML code for a JavaScript drop-down menu that contains various options, including "All Resumes". I am attempting to select this option using Selenium WebDriver: <div id="resume_freshness_container"> <div class="dropdown_small_wrapper ...

@vx/enhanced responsiveness with TypeScript

I am currently utilizing the @vx/responsive library in an attempt to retrieve the width of a parent component. Below are snippets from my code: import * as React from 'react' import { inject, observer } from 'mobx-react' import { IGlob ...

Can CSS Variables be changed globally using jQuery?

How can I dynamically change CSS Variables globally using jQuery? Check out this code snippet: $("div").click(function() { // Update the global variable "--text_color: rgb(0, 0, 255);" to a new value like "--text_color: rgb(0, 255, 255);" }); :roo ...

NPM TypeORM is throwing the error message "Duplicate migrations" when changes are made to a migration file

Recently, I made a modification to an existing table by adding a new column using the command npm run migration:generate <filename>. Unfortunately, I realized later on that I had misspelled the column name and needed to correct it (showComission -&g ...

The updates made in the $scope.$on event are not displaying in the view

Currently, when I am running a broadcast and trying to update a variable on the scope in order to display it on the view, the changes are not immediately reflected in the view. The UI needs to be clicked for the changes to show up. Can anyone suggest a s ...

Delete one item from a group of objects[]

In my TypeScript code, I have a declared object like this: public profileDataSource: { Value: string, Key: number }[]; This results in an object structure that looks similar to the following: 0: Object {Value: "<Select Profile>", Key: null} ...

When Highcharts and AngularJS team up, beware of the memory leak!

I've integrated highcharts into my AngularJS application using the highcharts-ng directive, but I'm encountering a persistent memory leak issue. My app is a slideshow with rotating slides that include charts. To investigate further, I created 3 ...

Raphael and jQuery/JavaScript for user-selected array intersections

Hello everyone! This is my first time posting here, and I must say that I'm still quite new to JavaScript/jQuery/Raphael. Please forgive me if I make any mistakes or ask basic questions. :) I've been searching high and low for answers to my quer ...

Performing an Ajax request upon the completion of page loading

I am currently working on creating a search functionality for a page, where users can input text into a search box and the page will display results based on their search. However, I am facing some timing issues as the blank search page is loading before ...

Ways to create distinct identifiers within a recurring function:

I am using this function twice: function (data) { $.each(data.items, function(i,item) { var $items = $('<div class="col-sm-4 grid-item"><div class="thumbnail"><input type="checkbox" name="thing_'+i+'" ...

Do the "Save to Drive" buttons require manual cleaning?

Utilizing the Google Drive API for JavaScript within a VueJS application can be done as follows: In your index.html <script type="text/javascript"> window.___gcfg = { parsetags: 'explicit', lang: 'en-US' }; </scri ...

Retrieve a Google map using Ajax in a PHP script

I'm attempting to display a google map on my homepage using the following function: function addressCode(id, concatenatedToShowInMap) { var geocoder; var map; geocoder = new google.maps.Geocoder(); ...

Utilize jQuery setInterval to dynamically add and remove classes on elements

My goal is to display my image in a way that resembles waving flames. I decided to achieve this effect by using two layers (flame tongues) stacked on top of each other in the same position. My initial approach was to hide one flame tongue while showing the ...

Add elements to an array with express, Node.js, and MongoDB

I'm currently learning about the MERN stack and I'm working on creating users with empty queues to store telephone numbers in E.164 format. My goal is to add and remove these numbers from the queue (type: Array) based on API requests. However, I ...

What is the process for saving an image from a Three.js canvas?

Can you provide tips on saving an image from a Three.js canvas? I'm having trouble making Canvas2Image work with Threejs. The issue seems to arise because the canvas object needs a div to be attached to before it is defined. Check out this resource ...

Is it possible that an issue with ui-router is causing Angular to crash Chrome on a local machine?

Encountering a peculiar issue with AngularJS in a local Windows environment. Utilizing two Angular-based bootstrap frameworks, Homer and Neuboard (links: homer and neuboard). Running both templates on Chrome locally causes the browser to freeze and consume ...

Ways to retrieve the initial value and proceed with a subsequent subscription method

I have created a basic angular 7 web application with Firebase database integration. In my code, I am attempting to store the initial list in an array using the subscribe method and then display that array using console.log(). However, there seems to be a ...

What is the best way to retrieve an ID when parsing JSON recursively?

Could you provide guidance on how to retrieve the IDs of all children when parsing JSON data? I have attempted to use a recursive function, but it seems to be calling infinitely. For reference, here is my code snippet: http://jsfiddle.net/Ds8vQ/ for(var ...

Learning how to interpret input from the command line in Vertx

Would appreciate some guidance on how to read command line arguments in vert.x using JavaScript. For instance, I am wondering how to go about reading: arguments(arg1, arg2, arg3) vertx run example.js arg1 arg2 arg3 ...