Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to mock angular translate filter in unit tests for directives

Tags:

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?

like image 675
jokomo Avatar asked Aug 20 '14 05:08

jokomo


People also ask

What is the use of angular routing in unit testing?

Angular Routing library, is that it provides a testing module for easier mocking in unit tests. I recommend that you do the same with components you want to create mocks for, by creating a *component-name*.component.mock.ts beside the component file, so you can easily get a mock of the component.

What is the best way to test AngularJS components?

AngularJS comes with dependency injectionbuilt-in, which makes testing components much easier, because you can pass in a component's dependencies and stub or mock them as you wish.

How do I create mocks for angular components?

What you will often see in Angular libraries, eg. Angular Routing library, is that it provides a testing module for easier mocking in unit tests. I recommend that you do the same with components you want to create mocks for, by creating a *component-name*.component.mock.ts beside the component file, so you can easily get a mock of the component.

When do I need to mock a component in unit testing?

Of course, if you have a test that needs to interact with another component, such as through a view child, you need to have a mock of the component, if you don’t want to create an integration test. What you will often see in Angular libraries, eg. Angular Routing library, is that it provides a testing module for easier mocking in unit tests.


1 Answers

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;
  };
});
like image 87
jokomo Avatar answered Oct 19 '22 19:10

jokomo