简体   繁体   中英

Error: No pending request to flush - when unit testing AngularJs service

I'm newbie to AngularJs, and I'm in the process of writing my first unit test; to test the service I wrote a test that simply returns a single Json object. However, everytime I run the test I get the error stated in the title. I don't know what exactly is causing this! I tried reading on $apply and $digest and not sure if that's needed in my case, and if yes how; a simple plunker demo would be appreciated.

here is my code

service

var allBookss = [];
var filteredBooks = [];

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

/*Retrive 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();// error is 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

I don't see where you're actually issuing a Report.query(). The getBook function just returns an unresolved promise that will never be resolved because nothing in the function is async.

You need to call Report.query via the book function with the promise resolved in the .then() (in the book function). After that, flush the http backend in the service.getBook().then() and do the expect.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM