Angularjs directives event broadcast unit testing

I've never had to check my angularjs directives before, and the directives I wrote for my current company are events that passed directives to directives and services.

And so I wrote a directive like. search directive.

<m-search />

      

This directive passes an event "searchbox-valuechanged"

and a key, now I have to write tests for it.

'use strict';

describe('<m-search>', function() {

  beforeEach(module('hey.ui'));
  var rootScope;
  beforeEach(inject(function($injector) {
    rootScope = $injector.get('$rootScope');
    spyOn(rootScope, '$broadcast');
  }));

  it("should broadcast something", function() {
    expect(rootScope.$broadcast).toHaveBeenCalledWith('searchbox-valuechanged');
  });

});

      

Update On change at input

<input class="m-input m-input--no-border" type="search" placeholder="Search"
       ng-model="ctrl.searchValue"
       ng-model-options="{debounce: 100}"
       ng-change="ctrl.onChange({search: ctrl.searchValue})">

      

It calls a method in a directive controller

vm.onChange = function (searchValue) {
  $rootScope.$broadcast('searchbox-valuechanged', {data: searchValue});
};

      

How can I check the broadcast?

+3


source to share


1 answer


This is how I would do it ...

describe('m-search directive', function() {
    var ctrl, // your directive controller
        $rootScope; // a reference to $rootScope

    beforeEach(function() {
        // bootstrap your module
        module('hey.ui');

        inject(function($compile, _$rootScope_) {
            $rootScope = _$rootScope_;
            // see https://docs.angularjs.org/api/ngMock/function/angular.mock.inject#resolving-references-underscore-wrapping-

            // create an instance of your directive
            var element = $compile('<m-search></m-search')($rootScope.$new());
            $rootScope.$digest();

            // get your directive controller
            ctrl = element.controller('mSearch');
            // see https://docs.angularjs.org/api/ng/function/angular.element#methods

            // spy on $broadcast
            spyOn($rootScope, '$broadcast').and.callThrough();
        });
    });

    it('broadcasts searchbox-valuechanged on change', function() {
        var searchValue = {search: 'search string'};
        ctrl.onChange(searchValue);

        expect($rootScope.$broadcast).toHaveBeenCalledWith(
            'searchbox-valuechanged', {data: searchValue});
    });
});

      



You will notice that this is independent of your directive template at all. I don't think the functionality of a template is in the realm of unit testing; that something is best left to test e2e with a protractor. Unit testing is testing the API of your components so that they do what they wanted to do.

+3


source







All Articles