1

我的控制器依赖于执行 http 请求的服务。控制器和服务测试都需要具有相同数据的 httpBackend。您对解决方法有任何想法吗?

4

1 回答 1

0

我想您的代码如下所示:

angular.module('MyApp', [])
    .controller('MyCtrl', function($scope, MyService) {
        $scope.doSomething = function() {
            MyService.doSomething();
        };
    })
    .service('MyService', function($http) {
        $http.get('some-url')
            .success(function(response) {
                // Handles the response
            });
    });

为了进行单元测试MyCtrl,您需要模拟其依赖项:$scopeMyService. 所以在你的测试中你可以这样做:

describe('MyCtrl', function() {
    var MyServiceMock,
        scope;

    beforeEach(function() {
        module('MyApp');

        // Creates a mock (spy) for MyService
        MyServiceMock = jasmine.createSpyObj('MyService', ['doSomething']); 

        inject(function($provide) {
            // Tells Angular to use MyServiceMock instead of MyService
            $provide.value('MyService', MyServiceMock);
        });

        inject(function($controller, $rootScope) {
            scope = $rootScope.$new();
            $controller('MyCtrl', { $scope: scope });
        });
    });

    it('calls doSomething of MyService', function() {
        $scope.doSomething();
        expect(MyServiceMock.doSomething).toHaveBeenCalled();
    });
});

这样您就可以进行测试MyCtrl,而无需使用MyService.

我假设您知道如何编写MyService使用该$httpBackend服务的测试,所以我不会在这里发布它的代码。

于 2013-08-14T14:35:12.393 回答