testing - 如何在 AngularJS 中为 servicesSpec 和 controllersSpec 定义全局 $httpBackend?

标签 testing angularjs httpbackend

我的 Controller 依赖于执行 http 请求的服务。 Controller 和服务测试都需要具有相同数据的 httpBackend。你有什么解决方法吗?

最佳答案

我想你的代码应该是这样的:

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 的实际实例。

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

关于testing - 如何在 AngularJS 中为 servicesSpec 和 controllersSpec 定义全局 $httpBackend?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18210682/

相关文章:

testing - 当 web api 仍在 iis 上运行时,如何在内存托管框架中使用组件测试 web api?

angularjs - 使用 httpBackend 的 Jasmine 测试未返回预期结果

iphone - 如何在 Windows 7 上安装配置文件进行测试

AngularJS:如何使用 id 作为 $scope 变量传递来添加/删除类?

grails - 如何将 AngularJS 与服务器端框架结合起来?

javascript - 将 Angular 范围变量传递给 Javascript

angularjs - 我如何期望不发出HTTP请求?

angularjs - 如何使 $httpBackend 对 URL 查询参数的顺序不敏感?

git工作流程: how to integrate and test feature branches without continuous delivery?

javascript - Jest setTimeout 不暂停测试