Search code examples
angularjskarma-jasmineangular-controllerkarma-coverageangular-unit-test

Not loading test cases generated in karma-jasmine framework


I am trying to write a simple test case for a controller, but it doesn't give any error as well doesn't load the test case I have written.

app.js

var myApp = angular.module('myApp',[ 'ui.bootstrap', 'dialogs', 'ui.router','base64','ngtimeago',
        'cfp.loadingBar', 'ngStorage', 'ngCookies', 'ngTable','ngRoute',
        'angularUtils.directives.dirPagination', 'ngSanitize','ngTagsInput',
        'ngIdle','angular.filter','angular-encryption','ngImgCrop']);

loginController.js

myApp.controller("loginController",['$scope','$rootScope','$state','APIServices','$http','$localStorage','cfpLoadingBar','$log','sha256','MFEEDBACK_CONSTANT_MESSAGES',
        function($scope, $rootScope, $state, APIServices, $http,$localStorage,cfpLoadingBar,$log,sha256) {
    var lc = this;
    lc.test = "hello";
}

loginController.specs.js

describe('Controllers', function(){
    beforeEach(module('myApp'));
    describe('loginController', function(){
        var loginController;
        beforeEach(inject(function($controller,$rootScope){
            var state,mockStorage,APIService,mockHTTP,mockLoadingBar,log,sha256,messages;
            var mockScope,mockRootScope = $rootScope.$new();
            loginController = $controller('loginController',{
                $scope:mockScope,$rootScope:mockRootScope,$state:state,APIServices:APIService,$http:mockHTTP,
                $localStorage:mockStorage,cfpLoadingBar:mockLoadingBar,$log:log,sha256:sha256,MFEEDBACK_CONSTANT_MESSAGES:messages
            });
        }));
        it('testCase1val should be working', function(){
            expect(loginController.test).toBe('hello');
        });
    });
});

getting output "Executed 0 of 0 ERROR (0.005 secs / 0 secs)"

getting output "Executed 0 of 0 ERROR (0.005 secs / 0 secs)"


Solution

  • I haven't added the third party dependencies, which I have in the app.js file. Most important thing is we need to add all required third party javascript file in 'karma.conf.js'. Then to add those dependencies in your unit test cases, we need to create mock javascript file and named as "ui.router.js".
    and make sure that file should contain following code.

    'use-strict';
    angular.module('ui.router', []);
    

    We need to create mock javascript file for each dependency declare in 'app.js' file and add those files in 'karma.conf.js'.
    Then load them before loading your app module as follows.

    beforeEach(function(){
       module('ui.router');
       module('ngTagsInput');
       .
       .
       .
       module('all your third party depedencies.');
    });
    beforeEach(module('myApp'));