AngularJS服务Jasmine单元测试未刷新请求错误

时间:2015-08-02 12:07:22

标签: angularjs unit-testing jasmine gulp karma-jasmine

我正在编写第一个单元测试来检查AngularJS服务的功能。这是使用getList功能测试的服务的一部分:

(function() {
'use strict';

angular
    .module('app.services')
    .factory('RestService', RestService);

    RestService.$inject = [ '$http' ];

    function RestService($http) { 

        var service = {
            getList: getList,
            ...
        };
        return service;

        function getList(url) {
            return $http.get(url)
            .then(function(response) {
                console.log('RestService: got list: ' + response.data.length);
                return response.data;
            })
            .catch(function(errResponse) {
                console.error('RestService: error getting list: ' + errResponse.status);       
            });
        }

我已经写了以下单元测试:

'use strict';

describe('Test Rest Service', function() {

var httpBackend;
var RestService;
var reqHandler;

beforeEach(module('app.services'));

beforeEach(inject(function ($httpBackend, _RestService_) {
    httpBackend = $httpBackend;
    RestService = _RestService_;
    reqHandler = httpBackend.when('GET', '/api/events')
                    .respond(200, '[{ "event": 1 }, { "event": 2 }]');
}));

afterEach(function() {
    httpBackend.verifyNoOutstandingExpectation();
    httpBackend.verifyNoOutstandingRequest();
});

it('should get a list of events', function() {

    var url = '/api/events';
    httpBackend.expectGET(url);
    RestService.getList(url).then(function(response) {
        httpBackend.flush();
        expect(response.length).toEqual(2);
    });
});
});

当我运行测试时,我收到以下错误:

Test Rest Service
PhantomJS 1.9.8 (Windows 8 0.0.0) Test Rest Service "after each" hook FAILED
    Error: Unflushed requests: 1

我的第一个猜测是,then部分测试没有执行,但我找不到检查方法。任何人都可以解释为什么我有一个不受欢迎的请求?此外,是否有某些方法可以逐步完成测试或至少将变量打印到屏幕上以便我可以弄清楚发生了什么?

提前致谢!

1 个答案:

答案 0 :(得分:8)

httpBackend.flush是函数,它导致来自httpBackend的返回数据。 你不能在那个块中调用它,因为接收数据时会调用它(在这种情况下永远不会)。

正确的测试代码是

it('should get a list of events', function() {

  var url = '/api/events';
  httpBackend.expectGET(url);
  RestService.getList(url).then(function(response) {
    expect(response.length).toEqual(2);
  });

  httpBackend.flush();

});

工作示例 - http://plnkr.co/edit/TA1HdQJaZHuShJiIIw6V?p=preview