Accessing $scope from unit test file when using the vm variable as this in Karma
code, webdev, angular, jasmine
September 16th 2015 (3 years ago)
Accessing $scope from unit test file when using the vm variable as this in Karma If you’re writing any AngularJS code, you propably know the Angular Style Guide from john papa, that says, that using “controllerAs with vm” ( var vm = this inside of controller ) is a good way to go – but when you’re starting to write tests, you may have a problem on how to get access to the scope istelf. There is a quick solution to that:

Let’s write a quick controller

(function() 
{
  'use strict';

  angular
  .module("playgroundApp")
  .controller("someCtrl", someCtrl);

  someCtrl.$inject = ['$scope'];

  function someCtrl($scope)
  {
    var vm = this;
    vm.exampleData = 'test';


    vm.init();

    //-----------------------------//

    vm.init = function()
    {
      console.log("initialized",vm.email);
    }
  }

})();

And now let’s write a test!

'use strict';
describe('someCtrl tests', function () {

    var scope,
        vm,
        someCtrl;

    beforeEach(function () {

        inject(function ($controller, $rootScope) {

            scope = $rootScope.$new();

            vm = $controller('someCtrl', {
                $scope: scope
            });
        });
    });

    describe('do some testing, booya!', function () {
        it('should check default data', function () {
            expect(vm.exampleData).toBe('test');
        });
    });
});


Basically, what we did is, we created a reference to our controller by assigning it to vm variable, this way, we can properly write tests and be consistent with the john papa’s styleguide.
Quite neat solution in my opinion :).