mardi 30 juin 2015

Unit testing controller with injected dependencies

  1. What is the best practice to inject the dependencies into my controller test?
  2. When would I use the module(function($provide){})?
  3. How do I properly check that $state.go() was called with the right arguments?

example-controller.js

angular.module('myModule')
    .controller('ExampleCtrl', ['$state', 'ExampleService', 'exampleResolve',
      function($state, ExampleService, exampleResolve){
        var self = this;

        self.property = false;
        self.resolvedProperty = exampleResolve;

        self.submit = function() {
          ExampleService
            .exampleGet()
            .$promise
            .then(function(res) {
              $state.go('anotherView', { prop1: 'yay', prop2: 'again' });
            })
        };
      }]);

example-controller.test.js

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

      var ctrl,
          mockBackend,
          mockState;

      var mockExampleResolve = { test: 'Test' };

      // Provide any mocks needed
      // when do I provide mocks?
      beforeEach(function() {
        module(function($provide) {

        });
      });

      beforeEach(inject(function($controller, $httpBackend, exampleResolve, $state) {
        mockBackend = $httpBackend;
        mockState = $state;
        exampleResolve = mockExampleResolve;

        ctrl = $controller('ExampleCtrl');
      }));

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

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

        it('should initialize any view-model variables', function() {
          expect(ctrl.property).toBe('false');
          expect(ctrl.resolvedProperty).toEqual({test: 'Test'});
        });
      });

      describe('submit called', function() {
        beforeEach(function() {

        });

        it('should call state.go with the correct arguments', function() {
           // how do i check this?
        });

      });

    });

Aucun commentaire:

Enregistrer un commentaire