How to mock a provider

My Angular 1.3 application uses the angular translation library . In my Karma tests, I try to make fun of the $translate provider with the Mock object I created.

The layout object is called MockTranslate and belongs to the myMocks module. I do not include the source for MockTranslate in the question since it is not relevant to the question.

My test topic is the controller, and I can easily make fun of $translate using the following:

 module('myMocks'); inject(function($controller, MockTranslate) { $controller("MyController", { $translate: MockTranslate.create(translations); }); }); 

The above is ridiculous work, however my preference would be to mock the provider using angular.mock.module with something like:

 module('myMocks'); module("myModule", function($provide) { $provide.provider("$translate", function(MockTranslate) { return MockTranslate.create(translations); }); }); 

But I get the following error while running my tests:

Error: [$injector:modulerr] Failed to instantiate module function ($provide) due to: Error: [$injector:unpr] Unknown provider: MockTranslate

How do I mock a provider using angular.mock.module ?

+6
source share
1 answer

If I understand the task correctly, here is a working example:

 angular.module('translateApp', []) .controller('translateCtrl', function ($scope, $translate) { $scope.translate = function(message) { return $translate.translate(message); }; }) .provider({ $translate: function() { this.$get = function () { return { translate: function (msg) { return 'OriginalTranslate: ' + msg; } }; }; } }); describe('Translate Controller Test', function() { var mockScope; var mockTranslate; beforeEach(module('translateApp', function($provide) { $provide.provider('MockTranslate', function() { this.$get = function () { return { translate: function (msg) { return 'MockTranslate: ' + msg; } }; } }); $provide.provider('$translate', function() { this.$get = function (MockTranslate) { return { translate: function (msg) { return MockTranslate.translate(msg); } }; } }); })); beforeEach(inject(function($controller, $rootScope, $translate) { mockScope = $rootScope.$new(); mockTranslate = $translate; $controller('translateCtrl', { $scope: mockScope, $translate: mockTranslate }); })); it('Translates messages', function () { expect(mockScope.translate('cool message')).toEqual('MockTranslate: cool message'); }); }); 
+19
source

Source: https://habr.com/ru/post/981174/


All Articles