错误:没有待清除的待处理请求 - 单元测试AngularJs服务时

时间:2014-08-17 22:45:23

标签: javascript angularjs karma-runner angular-mock

我是AngularJs的新手,我正在编写我的第一次单元测试;为了测试服务,我编写了一个只返回一个Json对象的测试。但是,每次运行测试时,我都会收到标题中声明的错误。我不知道究竟是什么造成了这个!我尝试在$apply$digest上阅读,并且不确定我的情况是否需要,如果是,如何;一个简单的plunker演示将不胜感激。

这是我的代码

服务

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;
}; 

测试

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: 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

1 个答案:

答案 0 :(得分:0)

我看不到你实际发布Report.query()的位置。 getBook函数只返回一个永远无法解析的未解析的promise,因为函数中没有任何东西是异步的。

您需要通过book函数调用Report.query,并在.then()(在book函数中)中解析promise。之后,刷新service.getBook()中的http后端。然后()并执行期望。