Error executing unit test in KarmaJS

0

Good afternoon,

When running the unit test in KarmaJS I have the following errors: I use AngularJS with RequireJS, AngularAMD and Instanbul.

  

ReferenceError: Can not find variable: module

And when I change the line in the test.spec.js file  for beforeEach(angular.mock.module('ng-app')); generates the following error.

  

ReferenceError: Can not find variable: angular

Below is the karma.conf.js configuration

basePath: '',
frameworks: ['jasmine', 'requirejs'],
reporters: ['progress', 'coverage'],
exclude: [],

files: [    
  { pattern: '../public/libs/jquery.min.js', included: false },
  { pattern: '../public/libs/angular/angular.js', included: false },    
  { pattern: '../public/libs/angular-1.3.15/angular-mocks.js', included: false},
  {pattern: '../public/app-admin/ng-controllers/**/*.js', included: false},     
  'test/test-main.js',
  'specs/*.spec.js'
],

preprocessors: {
  '**/../public/app-admin/ng-controllers/**/*.js': ['coverage']
},

port: 9876,

colors: true,

logLevel: config.LOG_INFO,

autoWatch: true,

browsers: ['PhantomJS'],

singleRun: false,

concurrency: Infinity,

coverageReporter: {
  includeAllSources: true,
  dir: 'test/coverage',
  reporters: [
    { type: "html", subdir: "html" },
    { type: 'text-summary' }
  ]
}

Test-main.js configuration

   var allTestFiles = [];
var TEST_REGEXP = /(spec|test)\.js$/i;

var pathToModule = function (path) {
var returnValue = path.replace(/^\/base\//, '').replace(/\.js$/, '');
return returnValue;
};

Object.keys(window.__karma__.files).forEach(function (file) {
if (TEST_REGEXP.test(file)) {
	allTestFiles.push(pathToModule(file));
}
});

require.config({

baseUrl: '/base',

paths: {
	'jquery': '../../public/libs/jquery.min',
	'angular': '../../public/libs/angular-1.4.3/angular',
	'angular-min': '../../public/libs/angular-1.4.3/angular.min',
	'angular-mock': '../../public/libs/angular-1.3.15/angular-mocks',
	'angular-route': '../../public/libs/angular/angular-route',

	// angularAMD libs
	'angularAMD': '../../public/libs/angularAMD/angularAMD',
	'ngload': '../../public/libs/angularAMD/ngload',

	// angular dependencies
	'ngUiRouter': '../../public/libs/angular/angular-ui-router',
	'ngUiSortable': '/app-admin/helpers/sortable',

	'angular-click-outside': '../../public/libs/angular-click-outside-master/clickoutside.directive',

	'moment': '../../public/libs/jquery-vendors/moment-develop/min/moment.min',

	// angular app
	'ng-app': '/app-admin/ng-app',

	// application helpers (js)
	'helper': '/app-admin/helpers',

	// paths to plugins to load the SRCs
	'text': '../../public/libs/require/text',
	'json': '../../public/libs/require/src/json',

	'route': '../../public/app-admin/routes',

	'jquery-vendor': '../../public/libs/jquery-vendors',

	// ng-modules path (angular)
	'ng-controller': '../../public/app-admin/ng-controllers',
	'ng-directive': '../../public/app-admin/ng-directives',

	'ng-model': '../../public/app-admin/ng-models',
	'ng-factory': '../../public/app-admin/ng-factories',
	'ng-service': '../../public/app-admin/ng-services',

	'test': '../specs'

},

// dynamically load all test files
deps: allTestFiles,

// we have to kickoff jasmine, as it is asynchronous
callback: window.__karma__.start
});

And finally my test.spec.js

describe("Test de spec", function () {

	 // load the controller's module
	 beforeEach(module('ng-app'));

	 var controller,
	   scope;
   
	 // Initialize the controller and a mock scope
	 beforeEach(inject(function ($controller, $rootScope) {
	   scope = $rootScope.$new();
	   controller = $controller('headerAreaController', {
		 $scope: scope
	   });
	 }));
   
	 it('Teste', function () {
		var a = true;
		expect(a).toBe(true)
	 });

});

Here is the error that is shown in the console

PhantomJS 2.1.1 (Windows 8 0.0.0) ERROR
  {
    "message": "An error was thrown in afterAll\nReferenceError: Can't find variable: module in http://localhost:9877specs/teste.spec.js (line 4)\nhttp://localhost:9877specs/teste.spec.js:4:20\n<Jasmine>",
    "str": "An error was thrown in afterAll\nReferenceError: Can't find variable: module in http://localhost:9877specs/teste.spec.js (line 4)\nhttp://localhost:9877specs/teste.spec.js:4:20\n<Jasmine>"
  }
PhantomJS 2.1.1 (Windows 8 0.0.0): Executed 0 of 0 ERROR (0.043 secs / 0 secs)

=============================== Coverage summary ===============================
Statements   : 0.48% ( 89/18571 )
Branches     : 0% ( 0/8490 )
Functions    : 0% ( 0/2909 )
Lines        : 0.48% ( 89/18555 )
================================================================================

And the other error when you change the line beforeEach(angular.mock.module('ng-app'));

PhantomJS 2.1.1 (Windows 8 0.0.0) ERROR
  {
    "message": "An error was thrown in afterAll\nReferenceError: Can't find variable: angular in http://localhost:9877specs/teste.spec.js (line 4)\nhttp://localhost:9877specs/teste.spec.js:4:20\n<Jasmine>",
    "str": "An error was thrown in afterAll\nReferenceError: Can't find variable: angular in http://localhost:9877specs/teste.spec.js (line 4)\nhttp://localhost:9877specs/teste.spec.js:4:20\n<Jasmine>"
  }
PhantomJS 2.1.1 (Windows 8 0.0.0): Executed 0 of 0 ERROR (0.043 secs / 0 secs)

=============================== Coverage summary ===============================
Statements   : 0.48% ( 89/18571 )
Branches     : 0% ( 0/8490 )
Functions    : 0% ( 0/2909 )
Lines        : 0.48% ( 89/18555 )
================================================================================

Thank you in advance!

    
asked by anonymous 05.07.2018 / 19:23

1 answer

0

I have resolved using this information from this site link

File: specs.js

define(['angular'], function(angular){

describe('Unit: Testing RequireJS', function(){
   var ctrl;
   var scope;
   var rootScope;

beforeEach(angular.mock.module('nome-do-controller'));

beforeEach(angular.mock.inject(function($rootScope){
    scope = $rootScope.$new();
    rootScope = $rootScope;
}));

});
});

File: main.js

require.config({

paths: {
    /* ABC order */
    'angular': 'vendor/angular/1.2.0/angular.min'
},
shim: {
    'angular': { exports: 'angular' },

    'app/controllers': { deps: ['angular'] }
}
});

File: test-main.js

// This creates an array of all the files that Karma finds with a suffix of
// Test.js (eg utilsTest.js) to be added to the Require JS config below
var tests = [],
file;
for (file in window.__karma__.files) {
if (window.__karma__.files.hasOwnProperty(file)) {
    if(/spec\.js$/.test(file)) {
        tests.push(file);
    }
}
}
requirejs.config({
baseUrl: '/base/public/javascripts/',  // Karma serves files from /base/<your-base-path>
    paths: {
        /* ABC order */
        'angular': 'vendor/angular/1.2.1/angular.min'

    },
    shim: {
        'angular': { exports: 'angular' },
        'app/controllers': { deps: ['angular'] },           
         },
deps: tests,  // add tests array to load our tests

callback: window.__karma__.start  // start tests once Require.js is done
});

File: karma.conf.js

//Karma configuration
module.exports = function (config) {
config.set({
// base path, that will be used to resolve files and exclude
basePath: '',

// Fix for "JASMINE is not supported anymore" warning
frameworks: ["jasmine", "requirejs"],

// list of files / patterns to load in the browser
files: [
    'vendor/angular/1.2.1/angular.js',
    'jquery-1.7.1.min.js',
    'test/spec/**/*.js',
    'test/test-main.js'
],

preprocessors: {
    'app/**/*.js': 'coverage'
},

// list of files to exclude
exclude: ['app/main.js'],

// test results reporter to use
// possible values: dots || progress || growl
reporters: ['progress', 'coverage'],

coverageReporter : {
    type: 'html',
    dir: 'coverage/'
},


// web server port
port: 9876,

// cli runner port
runnerPort: 9100,

// enable / disable colors in the output (reporters and logs)
colors: true,

// level of logging
// possible values: LOG_DISABLE || LOG_ERROR || LOG_WARN || LOG_INFO || LOG_DEBUG
logLevel: config.LOG_INFO,

// enable / disable watching file and executing tests whenever any file changes
autoWatch: false,

// Start these browsers, currently available:
// - Chrome
// - ChromeCanary
// - Firefox
// - Opera
// - Safari (only Mac)
// - PhantomJS
// - IE (only Windows)
browsers: ['Chrome'],

browserNoActivityTimeout: 100000,
// If browser does not capture in given timeout [ms], kill it
captureTimeout: 20000,

// Continuous Integration mode
// if true, it capture browsers, run tests and exit
singleRun: true
  });
 }
    
03.08.2018 / 12:34