4

I would like to test a directive, which has a filter dependency. I would like to inject actual filter, instead of using a mock.

Here is my mocked beforeEach. How do I go about injecting actual filter? I've tried injecting as part of the inject function, but this does not seems to work.

beforeEach(function() {

    // filter mock
    someFilterMock = function(value) {
        return value;
    };

    // get app
    module('app');
    // get html templates
    module('templates');

    // replace filter with a mock
    module(function($provide) {
        $provide.value('someFilterFilter', someFilterMock);
    });

    // inject & compile
    inject(function($rootScope, $compile) {
        // create scope
        scope = $rootScope.$new();
        // create element using directive
        element = angular.element('<this-is-directive />');
        $compile(element)(scope);
        scope.$digest();
    });

});
hunch_hunch
  • 2,283
  • 1
  • 21
  • 26
Iladarsda
  • 10,640
  • 39
  • 106
  • 170
  • Where does actual someFilterFilter reside (module)? Is it included in karma config? – André Werlang Nov 18 '14 at 13:59
  • it's part of the `angular.module('app')`, it's included in karma, I am loading all files. Is there any way I can verify this? – Iladarsda Nov 18 '14 at 14:04
  • 1
    Run karma on chrome, set singleRun: false on karma.conf.js and look for your code on Sources tabof chrome dev tools. – André Werlang Nov 18 '14 at 14:20
  • @Werlang - very good tip! thanks for that. Is there any way to unittest if directive/filter code has been provided? i.e. expect(directive).toBeDefined() – Iladarsda Nov 18 '14 at 14:39
  • Possible duplicate of [How to mock angular translate filter in unit tests for directives](http://stackoverflow.com/questions/25397515/how-to-mock-angular-translate-filter-in-unit-tests-for-directives) – Mario Levrero Mar 25 '16 at 07:44

1 Answers1

1

I am doing something like this in my tests:

it('uses a filter', inject(function ($filter) {
    var result = $filter('filterName')(params);
    expect(result).toBe('something');
}));

Perhaps it does help?

timtos
  • 2,225
  • 2
  • 27
  • 39
  • The filter would have its own unit test using the approach you provided. But OP stated he want to test a directive, not a filter. – André Werlang Nov 18 '14 at 14:18
  • 1
    Filter is being used inside the directive template, hence it's needs to be provided to directive. – Iladarsda Nov 18 '14 at 14:40