Search code examples
angularjsunit-testingjasminekarma-jasmineangular-mock

How to test $scope in Jasmine test?


I trying to write unit tests for Angularjs with Jasmine. Here is my controller:

function HomeController($scope, fav, news, materials) {
    console.log('home controller');
    $scope.testMe = true;
}

module.controller('HomeController', HomeController);

And tests

describe('Home controller tests', function() {
    var $rootScope, $scope, controller;

    beforeEach(function() {
        module('ap.designer');

        inject(function($injector) {
            $rootScope = $injector.get('$rootScope');
            $scope = $rootScope.new();
            controller = $injector.get('$controller')('HomeController', {$scope: $scope});
        });
    });

    describe('test controller functions', function() {
        it('Should return true', function() {
            expect($scope.testMe).toBe(true);
        });
     });
});

The test failed even if I trying to test expect(true).toBe(true);

Jasmine, Karma, Angular and Angular-mocks is inside my index.html in jasmine debug page, script with tests also.

I found that if I delete beforeEach() block, expect(true).toBe(true) passed.

Here is an error:

minErr/<@http://localhost:9876/base/bower_components/angular/angular.js:68:12
forEach@http://localhost:9876/base/bower_components/angular/angular.js:322:11
loadModules@http://localhost:9876/base/bower_components/angular/angular.js:4548:5
createInjector@http://localhost:9876/base/bower_components/angular/angular.js:4470:19
workFn@http://localhost:9876/base/bower_components/angular-mocks/angular-mocks.js:2954:44
angular.mock.inject@http://localhost:9876/base/bower_components/angular-mocks/angular-mocks.js:2934:35
@http://localhost:9876/base/src/js/modules/ap.designer/test/controllers/home/HomeControllerSpec.js:12:9
window.__karma__.loaded@http://localhost:9876/debug.html:42:9
@http://localhost:9876/debug.html:78:5

Solution

  • Check your module dependencies. maybe one of your dependencies not loaded in karma config files section, so your module creation failed.