How to mock angular translate filter in unit tests for directives
Asked Answered
D

4

20

In my directive templates, I need to use the angular translate filter as such:

    <label for="data-source-btn">
      <span id="data-source-btn-span"></span>
      {{'Data Source' | translate}}
    </label>

Then in my unit test for this directive, I get the error:

Unknown provider: translateFilterProvider <- translateFilter

I've tried injecting $filter and getting $translate by $translate = $filter('translate'); which doesn't solve the problem - this is really for testing the filter

I can inject the module pascalprecht.translate, but that is heavy handed. How do I best mock the filter?

Dutcher answered 20/8, 2014 at 5:47 Comment(0)
D
51

Below is a simple example of how you can mock the filter.

var mockTranslateFilter;

beforeEach(function() {
  module(function($provide) {
    $provide.value('translateFilter', mockTranslateFilter);
  });

  mockTranslateFilter = function(value) {
    return value;
  };
});
Dutcher answered 20/8, 2014 at 5:47 Comment(2)
Can I actually mock a translation here?Smoothbore
When using this I still get a Failed to instantiate module app.translate due to: Unknown provider: $translateProvider.Capuchin
S
0

This is working for me. But of course you should set mockTraslateFilter value to function bewfore you will use it in another funciton.

var mockTranslateFilter;

beforeEach(function() {
  mockTranslateFilter = function(value) {
    return value;
  };
  module(function($provide) {
    $provide.value('translateFilter', mockTranslateFilter);
  });
});

even shorter, if you use ES6:

    beforeEach(angular.mock.module(progressBarComponent, ($provide) =>      {
        $provide.value('translateFilter', (v) => v);
    }));
Sphygmomanometer answered 29/11, 2016 at 13:18 Comment(0)
E
0

This is the ES6 way:

beforeEach(angular.mock.module('myModule'), ($provide) => {
    $provide.value('$translate', t => ({ then: cb => cb(t) }));
}));   

This does not mock the $translate.instant method. For this you could assign the function to a variable and then assign the angular.identity method to the instantproperty.

Eat answered 18/1, 2017 at 19:59 Comment(0)
J
0

The simple solution which worked for me is to add this line in your test file:

beforeEach(angular.mock.module('pascalprecht.translate'));
Jaime answered 1/4, 2020 at 9:21 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.