1

I am attempting to perform a unit test on this controller.

angular.module('app.dashboard', [])
.controller('DashboardController', ['$scope', 'myAppService'], function($scope, myAppService) {
    var _data = myAppService.requests.get(function() {
        $scope.requests = _data.requests;
    });
});

myAppService is a service based on ngResource.

I want to test for the number of requests. I spent all day figuring out how to get $httpBackend injected, now I'm hung up on properly measuring the data.

beforeEach(inject(function ($controller, $rootScope, $injector) {
    $httpBackend = $injector.get('$httpBackend');
    $httpBackend.when('GET', '/api/requests').respond(
        {requests: [{sender: 'joe', message: 'help'}, {sender: 'larry', message: 'SOS'}]}
    );
});
it('should have a properly working Dashboard controller', inject(function($rootScope, $controller, $httpBackend) {
    var $scope = $rootScope.$new();
    var ctrl = $controller('DashboardController', {
        $scope : $scope
    });
    expect($scope.requests.length).toBe(2);
}));

Any assistance would be greatly, massively appreciated.

4

1 回答 1

3

在大多数情况下,一切看起来都很好。不过,我认为您的代码中可能缺少两件事。

首先,这种方法看起来不太正确:

var _data = myAppService.requests.get(function() {
        $scope.requests = _data.requests;
    });

如果您提供回调函数,那不应该传入数据:

myAppService.requests.get(function(_data) {
    $scope.requests = _data.requests;
});

myAppService如果没有看到您的代码(即使用$resource) ,很难判断。

其次,为了刷新 ajax 响应,您需要$httpBackend.flush();在使用 expect 进行断言之前调用:

    var $scope = $rootScope.$new();
    var ctrl = $controller('DashboardController', {
        $scope : $scope
    });
    httpBackend.flush();
    expect($scope.requests.length).toBe(2);

$httpBackend 文档

flush(count): 使用经过训练的响应刷新所有待处理的请求。

希望这可以帮助。

于 2013-11-05T23:30:49.033 回答