lundi 29 juin 2015

Unit testing $http resolve in controller

I need help with my controller test. I have a resolve using ui-router. In my test, I need to figure out how to handle the resolve's exampleData.

config.js

angular.module('myModule')
  .config(['$stateProvider', '$urlRouterProvider',

    function($stateProvider, $urlRouterProvider) {

      $stateProvider
        .state('site', {
          abstract: true,
          resolve: {
            exampleData: function(ExampleService) {
              // ExampleService.get() makes an $http call
              return ExampleService.get();
            }
          },
          // etc
        })
        .state('example', {
          parent: 'site',
          url:'/example',
          controller: 'ExampleCtrl as example',
          templateProvider: function($templateCache) {
            return $templateCache.get('views/example.html');
          }
        });

    }]);

example-controller.js

angular.module('myModule')
  .controller('ExampleCtrl', ['exampleData',
     function(exampleData) {

       var self = this;
       self.exampleData = exampleData;

       // self.exampleData should output something like
       // [
       //   {id: 1, title:'something'},
       //   {id: 2, title:'something'},
       //   {id: 3, title:'something'}
       // ]

  }]);

example-controller.test.js

   describe('Controller: ExampleCtrl', function() {
      beforeEach(module('myModule'));

      var ctrl;

      beforeEach(inject(function($controller) {
        ctrl = $controller('ExampleCtrl');
      }));

      describe('initialization', function() {
        beforeEach(function() {});

        it('should exist', function() {
          expect(!!ctrl).toBe(true);
        });

        it('should ...', function() {
          // do something
        });
      });

When I run the tests, I get the following error:

Unknown provider: exampleDataProvider <- exampleData <- ExampleCtrl

My question is: what do I do in order to test the resolve in my ExampleCtrl? The ExampleService.get() is a service which makes an $http call and returns and array of objects.

Aucun commentaire:

Enregistrer un commentaire