Issue: A request is not pending for flushing during the testing of an AngularJs service

As a beginner in AngularJs, I am currently working on my first unit test. In order to test the service I created, I wrote a test that simply returns a single Json object. However, whenever I run the test, I encounter the error mentioned in the title. I am unsure about what is causing this! I have tried to understand $apply and $digest, but I am not certain if they are necessary in my case and how to implement them; a demonstration on plunker would be helpful.

Here is my code:

Service


var allBooks = [];
var filteredBooks = [];

/* Defining the book model and REST api */
var Report = $resource('api/books/:id', {
     id: '@id'
}, {
     query: {
            method: 'GET',
            isArray: false
     }
});

/* Retrieve the requested book from the internal book list */
var getBook = function(bookId) {
      var deferred = $q.defer();

       if (bookId === undefined) {
           deferred.reject('Error');
       } else {
           var books= $filter('filter')(allBooks, function(book) {
              return (book.id == bookId);
           });

           if (books.length > 0) {
                deferred.resolve(books[0]); //returns a single book object
            } else {
                deferred.reject('Error');
            };
         };
 return deferred.promise;
}; 

Test


describe('unit:bookService', function(){

beforeEach(module('myApp'));
var service, $httpBackend;

beforeEach(inject(function (_bookService_, _$httpBackend_) {
    service = _bookService_;
    $httpBackend = _$httpBackend_;
    $httpBackend.when('GET', "/api/books/1").respond(200, {
        "book": {
            "id": "1",
            "author": "James Spencer",
            "edition": "2",
            .....
        }
    });
}));
afterEach(function() {
    $httpBackend.verifyNoOutstandingExpectation();
    $httpBackend.verifyNoOutstandingRequest();
});
it('should return metadata for single report', function() {
      service.getBook('1').then(function(response) {
               expect(response.length).toEqual(1);
           });
    $httpBackend.flush(); // The error occurs in this line
});
});

Error


Error: No pending request to flush !
    at c:/myapp/bower_components/angular-mocks/angular-mocks.js:1439
    at c:/myapptest/tests/bookTest.js:34

Libs Version

AngularJS v1.2.21

AngularJS-mock v1.2.21

Answer №1

It appears that you are missing the step of actually calling Report.query(). The getBook function seems to just return an unresolved promise without any async operations, meaning it will not be resolved.

To fix this issue, remember to invoke Report.query inside the book function and resolve the promise in the .then() block. Then, make sure to flush the http backend in service.getBook().then() before proceeding with the expect statement.

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

Include images in the form of .png files within the td elements of a table that is dynamically generated in the index

I have successfully created a table using embedded JavaScript with the help of messerbill. Here is the code: <table id="Table1"> <tr> <th>Kickoff</th> <th>Status</th> <th>Country</th> < ...

Enhance Your HTML Skills: Amplifying Table Display with Images

Recently, I utilized HTML to design a table. The Table Facts : In the first row, I included an appealing image. The second row contains several pieces of content. In continuation, I added a third row. The contents in this row are extensive, resulting i ...

What is the best way to generate a new DIV every time a button is clicked?

I am attempting to make a square DIV that is red and measures 100x100 pixels. Each time a button is clicked, I want the square to be created. However, the code I have written is not functioning properly: <html> <title> Create New Div ...

The dynamic form functionality is experiencing issues when incorporating ng-container and ng-template

I'm currently working on a dynamic form that fetches form fields from an API. I've attempted to use ng-container & ng-template to reuse the formgroup multiple times, but it's not functioning as anticipated. Interestingly, when I revert b ...

Iterate through the xml.documentElement in a loop

I want to show 8 men and 2 women in SVG format. However, my current function only displays one man and woman. How can I add a loop to make this work for all individuals? for (i = 0; i < Serie[n].Number; i++) { return xml.documentElement } The data arr ...

Validating forms in express.js

I need to validate a form that includes user details. In addition to the basic validation for checking if fields are not empty, I also want to verify if the username/email exists in the database. For the email field, I need to ensure it is not empty, follo ...

Updating the background image with Jquery is resulting in a distracting flicker effect

Here is a snippet of the script I'm using to create a slider that changes the background image for each image object in a specified time cycle. #Sliderimg - height set to 500px, $("#Sliderimg").css({ "background-image": "url(../Images/" + SliderIma ...

Using Angular: connecting $viewContentLoaded to manually initiate app bootstrapping

I have an Angular module that I am bootstrapping manually and attempting to access its $rootScope to add an event listener for $viewContentLoaded. Below is the code snippet: angular.bootstrap(el, [appname]); //////////////////////////// Fixing links cons ...

How can PHP effectively interpret JSON strings when sent to it?

When working with JavaScript, I am using JSON.stringify which generates the following string: {"grid":[{"section":[{"id":"wid-id-1-1"},{"id":"wid-id-1-4"}]},{"section":[{"id":"wid-id-1-5"}]},{"section":[{"id":"wid-id-1-2"},{"id":"wid-id-1-3"}]}]} I am ma ...

Retrieve information in JSON format from a document

I'm trying to extract data from a JSON file without knowing the exact location of the data. Here is an example JSON: var names= [ { "category":"category1" , "name1":"david", "name2":"jhon", "name3":"peter" }, { "category":"catego ...

Add motion to the div element when hovering and moving the mouse away

Looking to add animation to a list moving from left to right and vice versa. Now, I want the list to animate from left to right when the mouse hovers over the div, and then animate from right to left when the mouse leaves the div. Can someone assist me wit ...

Jest test encounters an error due to an unexpected token, looking for a semicolon

I've been working on a Node project that utilizes Typescript and Jest. Here's the current project structure I have: https://i.stack.imgur.com/TFgdQ.png Along with this tsconfig.json file "compilerOptions": { "target": "ES2017", "modu ...

Exploring the power of jQuery and Ajax together

Today seems to be one of those days where even the simplest tasks become a challenge. I'm sorry if this question has been asked before, but I'm struggling with a basic issue. I want to dynamically update text on a website using a text file, and w ...

Populate the browser screen with a series of unpredictable numbers

I'm looking to fully populate the visible window of a webpage with random numbers. My current approach involves generating a long string of random digits first, and then applying the following properties to a div: #mydiv{ font-family: "Inconso ...

I would prefer not to add another database table just to differentiate between team members and friends. Can you provide assistance with this?

Instead of creating another table named friends in Strapi and linking it to Visual Studio Code, I have opted to use a Characters table for both team members and friends. This way, I can input new data only at Characters and filter it to differentiate betwe ...

Getting the URL path within getStaticPaths in Next.js

Is there a way to retrieve the last number from the current URL pathnames in getStaticPaths? http://localhost:3000/category/food/2 -> 2, http://localhost:3000/category/food/3 -> 3, ... I have attempted: export const getStaticPaths: GetStaticPaths = ...

Combining Javascript and Django for a powerful web development solution

Having trouble setting up JS on my Django web app, despite reading through the documentation and previous queries. Using the Django dev server with the following file structure: mysite/ __init__.py MySiteDB manage.py settings.py ...

Guide on modifying a field in a table when a checkbox is selected using Angular

I have a task that involves updating the fields in a database table to TRUE (boolean field) when a checkbox is checked, and FALSE when unchecked. Below is the code for the checkbox in my Angular HTML page: <checkbox-field attribute='updateExistin ...

Utilize ReactJS and AJAX to easily upload images

Having trouble with uploading an image through a form to a url/api. When I submit the form, I'm calling the handleImgUpload() method. The issue is that the request being sent is coming back empty. Seems like there might be a problem with new FormData ...

Implementing dynamic components in Vuejs by passing props from objects

I have developed a dashboard application that allows users to customize their dashboard by adding widgets in any order. While the functionality is working fine, I am looking to address some technical debt and clean up the code. Let's simplify things ...