0

Boa tarde,

Ao rodar o teste unitário no KarmaJS tenho como retorno os seguintes erros: Utilizo AngularJS com RequireJS, AngularAMD e Instanbul.

ReferenceError: Can't find variable: module

E quando altero a linha no arquivo test.spec.js para beforeEach(angular.mock.module('ng-app')); gera o seguinte erro.

ReferenceError: Can't find variable: angular

Abaixo segue a configuração do karma.conf.js

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

Configuração do 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
});

E por fim meu 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)
	 });

});

Aqui é o erro que é mostrado no 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 )
================================================================================

E o outro erro quando é alterado a linha 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 )
================================================================================

Obrigado desde já!

2
  • provavelmente o problema está nos imports no seu projeto, veja aqui se é a solução: stackoverflow.com/questions/44682587/…
    – Melissa
    Commented 12/07/2018 às 18:17
  • Oi, eu cheguei a acessar este link que me mandou e também não funcionou =/
    – Danilo
    Commented 13/07/2018 às 16:37

1 Resposta 1

0

Resolvi utilizando essas informações deste site http://qaru.site/questions/160933/getting-mismatched-anonymous-define-module-when-i-try-running-tests

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

});
});

Arquivo: main.js

require.config({

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

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

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

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

1
  • Seria interessante colocar os códigos que utilizou para resolver o problema aqui. Facilita a busca futura e caso o site de referência saia do ar, não se perde a solução. Considere editar sua resposta Commented 3/08/2018 às 11:23

Você deve fazer log-in para responder a esta pergunta.

Esta não é a resposta que você está procurando? Pesquise outras perguntas com a tag .