Error running unit test in Karmajs

Asked

Viewed 446 times

0

Good afternoon,

When running the unit test in Karmajs I have as return the following errors: Using Angularjs with Requirejs, Angularamd and Instanbul.

Referenceerror: Can’t find variable: module

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

Referenceerror: Can’t find variable: angular

Below follows the configuration of karma.confjs.

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' }
  ]
}

Configuration of test-main.js

   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.specjs.

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 the line is changed 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 )
================================================================================

Thanks in advance!

  • the problem is probably in the Mports in your project, see here if it is the solution: https://stackoverflow.com/questions/44682587/karma-error-cant-find-variable-angular

  • Hi, I got access to this link you sent me and also did not work =/

1 answer

0


I resolved using this information from this site http://qaru.site/questions/160933/getting-mismatched-anonymous-define-module-when-i-try-running-tests

Archive: 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'] }
}
});

Archive: 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
  });
 }

  • It would be interesting to put the codes you used to solve the problem here. Facilitates future search and if the reference site goes off the air, the solution is not lost. Consider editing your answer

Browser other questions tagged

You are not signed in. Login or sign up in order to post.