How to mock angular translate filter in unit tests for directives

前端 未结 4 846
说谎
说谎 2020-12-05 14:29

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

    
相关标签:
4条回答
  • 2020-12-05 14:53

    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.

    0 讨论(0)
  • 2020-12-05 14:56

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

    beforeEach(angular.mock.module('pascalprecht.translate'));
    
    0 讨论(0)
  • 2020-12-05 14:57

    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;
      };
    });
    
    0 讨论(0)
  • 2020-12-05 15:02

    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);
        }));
    
    0 讨论(0)
提交回复
热议问题