mercredi 22 février 2017

Angular - Not passing $controller in callback of 'it' function fails test, why?

A bit of a testing newbie here, I'm trying to write some Jasmine/Karma tests for a controller. I was given a sample test to work with and build off of, and here, the $controller was passed in the argument for the function of the it block. This causes the test to pass fine.

I've successfully written tests for other controller for this app and I haven't seen $controller ever passed in there. So I try to follow what I know, but the moment I remove the $controller, the test fails because it's looking for the dependencies (which I should be giving via $provide.value in the beforeEach...?).

Here's the controller code -

(function() {
  'use strict';

  angular
    .module('myApp')
    .controller('EntryAddController', EntryAddController);

  function EntryAddController($scope, $state, moment, $sanitize, dogList, catList, months, frequencies, EntryFactory, $modal, toastr, $log) {
    var vm = this;
    var now = moment();
    var tomorrow = now.add(1, 'days').toDate();
    var to = now.subtract(1, 'days').add(12, 'months').toDate();

    vm.fromDay = tomorrow;
    vm.minDay = tomorrow;

    start();

    function start() {
      //some logic here
    }
})();

Here's the sample code I was given (note the it block) -

(function() {
  'use strict';



describe('Entry Add Controller', function(){

    describe('EntryAddController', function() {

      var vm, $rootScope, $controller;

      beforeEach(module('myApp'));

      beforeEach(function() {
        inject(function(_$rootScope_, _$controller_) {
          $rootScope = _$rootScope_;
          $controller = _$controller_;
        });
      });

      describe('EntryAddController', function() {
        var $scope;

        beforeEach(function createChildScopeForTheTest() {
          $scope = $rootScope.$new();
        });

        afterEach(function disposeOfCreatedChildScope() {
            $scope.$destroy();
        });

        it('expects fromDate and toDate to be defined', function($controller) {
            vm = $controller('EntryAddController', { $scope: $scope });

            expect(vm.fromDay).toBeDefined();
        });

      });
    });
  });

})();

So why is it that when I remove $controller from the argument of the function in the it block, it throws this error?

Error: [$injector:unpr] Unknown provider: dogListProvider <- dogList <- EntryAddController

What is the difference between these two versions of the it block?

it('expects fromDate and toDate to be defined', function($controller) {
   vm = $controller('EntryAddController', { $scope: $scope });

   expect(vm.fromDay).toBeDefined();
});

vs.

it('expects fromDay to be defined', function() {
   vm = $controller('EntryAddController', { $scope: $scope });

   expect(vm.fromDay).toBeDefined();
});

Aucun commentaire:

Enregistrer un commentaire