How to mock a service in AngularAMD app unit tests

232 Views Asked by At

I have an angular app using AngularAMD with require.js. I want to mock a service like here:

module(function ($provide) {
    $provide.service('ToolsService', function () {
        var toolsServiceMock = {
          someMethod: function () { }
        };
        return toolsServiceMock;
    });
});

And inject it like:

angularAMD.inject(function ($injector) {
    toolsService = $injector.get('ToolsService');
});

But $injector gives me real service instead of my mock. Also the function($provide) is never called.

When I change angularAMD.inject() to angular inject() I get the mock, but other application components don't work.

How can I tell angularAMD to use mocks instead of real implementations?

1

There are 1 best solutions below

2
On

You can do the following to test the service with angularAMD.

define(['app','angularAMD'],function(app,angularAMD){
    'use-strict';
    describe('ToolsService',function(){
        // load the controller's module
        beforeEach(angular.mock.module('appModule'));
        var moduleToInject;
        // Initialize the controller and a mock scope
        beforeEach(function(){
            angularAMD.inject(function ('ToolsService') {

            });
        }); 
        it('should check all methods', function() {

            //code to test


        });
    });
});