0

我对 AngularJS 和测试很陌生,所以我试图测试我在 AngularJS 中制作的服务。

我已经设置了这样的服务

var serviceModule = angular.module('App.services', []);
serviceModule.factory('subscribeService', function ($http) {
    return {
        getNumberOfSubscribers : function() {
            return $http.get('/jsonFiles/subscribers.json')
                .then(function(subscribers) {
                     return subscribers.length;
                });
        }
    };
});

测试是这样进行的。

describe('Subscribe service test', function() {
var httpBackend,
    subscribeServiceMock, 
    subscribers;

subscribers = [{"email": "test1@mail.com", "subscriptions": "A,B,C"},
               {"email": "test2@mail.com", "subscriptions": "A,C,D"},
               {"email": "test3@mail.com", "subscriptions": "B,C,F"}];

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

beforeEach(inject(function(subscribeService){
    subscribeServiceMock = subscribeService;
}));

it('Should return total numbers of subsribers', inject(function ($httpBackend) {
    $httpBackend.whenGET('/jsonFiles/subscribers.json').respond(subscribers);
    var numberOfSubscribers = subscribeServiceMock.getNumberOfSubscribers();
    $httpBackend.flush();
    expect(numberOfSubscribers).toEqual(3);

}));

测试接缝因此错误而失败:“订阅服务测试应返回订阅者总数失败”“预期 { then : Function } to equal 3”

我想知道我哪里弄错了?

4

1 回答 1

0

您是否尝试过注入您的 httpBackend?在你的“beforeEach”电话上试试这个:

beforeEach(inject(function(subscribeService, _$controller_, _$rootScope_, _$httpBackend_){
    subscribeServiceMock = subscribeService;
    $scope = _$rootScope_.$new();
    $controller = _$controller_('MyCtrl', { $scope: $scope });
    $httpBackend = _$httpBackend_;
}));

更新

正如我在这里发现的那样:AngularJS Issues mocking httpGET request

看来这两种“注入方式”其实是有区别的

于 2013-08-06T14:23:07.597 回答