jeudi 1 septembre 2016

Spy on angular notify for unit test

I have a controller that uses a notify plugin (http://ift.tt/2cueecm) and I'm trying to unit test that notify({ message: 'an alert'}) was called after doing an ng-click.

Example

div(ng-click='myCtrl.showAlert()') Show alert

Controller

function MyCtrl(notify) {
    var vm = this;

    vm.showAlert = function() {
       notify({ message: 'an alert' });
    };
}

angular.module('main').controller('MyCtrl', ['notify', MyCtrl]);

Unit Test

describe('MyCtrl', function() {
   var $scope;
   var $controller;
   var ctrl;
   var notify;

   // etc boilerplate

   beforeEach(function() {
       inject(function(_$rootScope_, _$controller_, _notify_) {
           $scope = _$rootScope_.$new();
           $controller = _$controller_;
           notify = _notify_;
           ctrl = $controller('MyCtrl');
       });
   });

   describe('on click', function() {
     it('should call notify with the right message', function() {
         spyOn(notify).and.callThrough();
         ctrl.showAlert();
         expect(notify).toHaveBeenCalled();
     });
   });
});

But it's not working, and I'm not sure exactly how to mock out the notify dependency.

Aucun commentaire:

Enregistrer un commentaire