Injecting a mock service for an angularjs controller test

Viewed 16242

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.

Here's my current test:

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) {
    ...
}

so it's the speedSlider I want to mock.

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 = {
       ...
    };
});

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!

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....

4 Answers
Related