注入模拟服务为angularjs控制器测试

注入模拟服务为angularjs控制器测试

本文介绍了注入模拟服务为angularjs控制器测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想测试一个控制器,它取决于我自己建的服务。我想,因为服务谈判的DOM嘲笑这项服务。

I'm trying to test a controller that depends on a service I built myself. I'd like to mock this service since the service talks to the DOM.

下面是我目前的测试:

describe('Player Controllers', function () {

    beforeEach(function () {
        this.addMatchers({
            toEqualData: function (expected) {
                return angular.equals(this.actual, expected);
            }
        });
    });

    describe('TestPSPlayerModule', function () {
        var $httpBackend, scope, ctrl;

        beforeEach(module('PSPlayerModule'));

        beforeEach(inject(function (_$httpBackend_, $rootScope, $controller) {
            $httpBackend = _$httpBackend_;

            scope = $rootScope.$new();
            ctrl = $controller(PlayerController, { $scope: scope });
        }));

        it('should request a clip url from the server when clipClicked is called', function () {
            expect(1).toBe(1);
        });
    });

});

我的控制器看起来是这样的:

My controller looks like this:

w.PlayerController = function ($scope, $http, $window, speedSlider, $location) {
    ...
}

所以这是我想嘲笑speedSlider。

so it's the speedSlider I want to mock.

我有主意,用一个模块我在我的测试code创建了一个可以提供伪造实现速度滑块,所以我增加了以下到test.js文件的顶部:

I had the idea to use a module I created in my test code that could provide a faked implementation of the speed slider, so I added the following to the top of the test.js file:

module('TestPSPlayerModule', []).factory('speedSlider', function () {
    return = {
       ...
    };
});

,然后列出了beforeEach该模块()调用,而不是具体的一个,但如果我这样做,我得到了以下错误:

and then list that module in the beforeEach() call instead of the concrete one, but if I do that I get the following error:

Injector already created, can not register a module!

所以我想必须有我提供一个模拟实现我的服务之一的更好的方法。东西我可以或许用sinon.js的....

So I figure there must be a better way for me to provide a mock implementation of one of my services. Something I can perhaps use sinon.js for....

推荐答案

请确保当你使用它的定义之后模块,你没有多余的括号内。
因此,模块('TestPSPlayer')而不是模块('TestPSPlayer',[])

Make sure when you use module after its definition that you don't have the extra brackets.So module('TestPSPlayer') instead of module('TestPSPlayer',[]).

这篇关于注入模拟服务为angularjs控制器测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 22:28