How do you test the angle modulus defined inside IIFE with jasmine?

How can I test this module on jasmine? The problem is that it is very difficult to test $controller, because the function is hidden inside the closure, it is very difficult to test.

In other words, given the module definition below, writing a unit test for MainCtrl seems impossible.

(function () {

    'use strict';

    angular.module('app', []);

    function MainCtrl() {
      var mc = this;
      mc.obj = {
        val : 50  
      };
    }

    angular.module('app').controller('MainCtrl', MainCtrl);

} () );

and the "typical" jasmine test

describe('app', function(){

  beforeEach(module('app'));

  it('should create an objet with val 50', inject(function(_$controller_) {
    var scope = {},
        ctrl = _$controller_('MainCtrl', {$scope:scope});

    expect(scope.obj.val).toBe(50); // returns Expected undefined to be 50.
  }));

});

When angular enters the service _$controller_inside the jasmine test function, the instance of the created controller returns with an undefined $ scope.

So how can you test it?

My search on StackOverflow to solve this problem did not give me the answer I was looking for, so I implemented one of mine.

+4
2

, :

describe('app', function () {

    var $controller;

    beforeEach(function () {

        module('app');

        inject(function (_$controller_) {

            $controller = _$controller_('MainCtrl');

        });
    });

    //-- spec - test controller

    describe('Controller : MainCtrl', function () {

        it('should create an object with val 50', function () {

            expect($controller.obj.val).toBe(50);

        });
    });

});

jsfiddle

, !

+1

var scope = {}, ctrl = _$controller_('MainCtrl', {$scope:scope});

undefined. - :

  • Inject $rootScope: inject(function (_$controller_, _$rootScope_)

  • : var scope = $rootScope.$new();

  • : var ctrl = _$controller_('MainCtrl', {$scope: scope});

0

Source: https://habr.com/ru/post/1568274/


All Articles