I have a project that is using angularjs with requirejs and testing with karma. I am having trying with testing a service in the project.
These are my files that I have configured with angularjs, requirejs, and karma. When I run my service test I get this error TypeError: Cannot read property 'inject' of undefined. If I comment out the beforeEach part in the test code everything runs fine, but I can't do that in the real tests.
test-main.js
var allTestFiles = [], file;
for (file in window.__karma__.files) {
if (window.__karma__.files.hasOwnProperty(file)) {
if(/test\.js$/.test(file)) {
allTestFiles.push(file);
}
}
}
require.config({
baseUrl: '/base',
// alias library paths
// must set 'angular'
paths: {
'jquery': 'web/common/js/vendor/jquery-1.10.2/jquery-1.10.2.min',
/* common includes */
'angular' : 'web/common/js/vendor/angular/angular',
'angular-ui-router' : 'web/common/js/vendor/angular/angular-ui-router.min',
'angular-css-injector' : 'web/common/js/vendor/angular/angular-css-injector',
'angular-animate' : 'web/common/js/vendor/angular/angular-animate.min',
'angularAMD' : 'web/common/js/vendor/angular/angularAMD',
'ssss-abs-tpls' : 'web/common/js/sandbox/ssss-abs-tpls',
'angular-sanitize' : 'web/common/js/sandbox/angular-sanitize',
'modernizr' : 'web/common/js/vendor/modernizr/modernizr',
'scrollToPlugin' : 'web/common/js/vendor/ScrollToPlugin/ScrollToPlugin',
'TweenMax' : 'web/common/js/vendor/TweenMax/TweenMax',
'gestures' : 'web/common/js/vendor/gestures/gestures',
'ssss-base' : 'web/common/js/framework/ssss.base',
'hammer' : 'web/common/js/framework/hammer',
'angular-mocks' : 'web/common/js/vendor/angular/angular-mocks',
/* controllers,not listed*/
/* services */
'MyService' : 'app/services/models/MyService',
/* directives, not listed*/
/* router */
'MyApp' : 'app/MyApp',
/*utils*/
'Message' : 'app/utils/message'
},
/* For angular modules that do not support AMD out of the box, specify them in shim */
shim: {
'angular-ui-router' : ['angular'],
'gestures': ['angular'],
'angular-sanitize': ['angular'],
'angular-css-injector': ['angular'],
'angular-animate': ['angular'],
'ssss-session': ['angular'],
'ssss-abs-tpls' : ['angular','gestures','angular-sanitize'],
'angular-mocks' : ['angular']
},
/* kick start the application */
//deps: ['eMaintenance'],
deps: allTestFiles,
// we have to kickoff jasmine, as it is asynchronous
callback: window.__karma__.start
});
karma.conf.js
// Karma configuration
// Generated on Wed Nov 05 2014 15:22:19 GMT-0600 (Central Standard Time)
module.exports = function(config) {
config.set({
// base path that will be used to resolve all patterns (eg. files, exclude)
basePath: './',
// frameworks to use
// available frameworks: https://npmjs.org/browse/keyword/karma-adapter
frameworks: ['jasmine', 'requirejs'],
// list of files / patterns to load in the browser
files: [
{pattern: 'web/common/*.js', included: false},
{pattern: 'web/common/**/*.js', included: false},
{pattern: 'app/*.js', included: false},
{pattern: 'app/**/*.js', included: false},
{pattern: 'test/*.js', included:false},
{pattern: 'test/**/*.js', included:false},
{pattern: 'test-main.js', included: true}
],
// list of files to exclude
exclude: [
/*requirejs paths file*/
'app/main.js'
],
// preprocess matching files before serving them to the browser
// available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
preprocessors: {
},
// test results reporter to use
// possible values: 'dots', 'progress'
// available reporters: https://npmjs.org/browse/keyword/karma-reporter
reporters: ['progress'],
// web server port
port: 9876,
// enable / disable colors in the output (reporters and logs)
colors: true,
// level of logging
// possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
logLevel: config.LOG_INFO,
// enable / disable watching file and executing tests whenever any file changes
autoWatch: true,
// start these browsers
// available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
browsers: ['Chrome'],
// Continuous Integration mode
// if true, Karma captures browsers, runs the tests and exits
singleRun: false,
plugins:[
'karma-requirejs',
'karma-chrome-launcher',
'karma-jasmine',
'karma-phantomjs-launcher'
]
});
};
MyService.js
define(['myApp'], function (app) {
app.register.factory("MyService",["$http","$q", function($http, $q) {
getData:function(){
var data = {
"test1":"some data"
};
return {
then:function(myFunc){
myFunc(data);
}
};
}
};
}]);
});
MyService.test.js
define(['angular-mocks','MyApp','MyService'],
function (mocks, app, MyService) {
describe('MyService test', function(){
var service;
beforeEach(mocks.inject(function(MyService){
service = MyService;
}));
it('should do something', function(){
expect('abc').toBe('abc');
});
});
});
Just call inject not mocks.inject ! It should works now !
beforeEach(inject(function(MyService){
service = MyService;
}));
Related
I have a very simple test where I inject $http $q and $httpBackend then do nothing (yet).
It crashs on the inject and I cannot figure out why.
Here's my code :
/// <reference path="../references.spec.ts" />
module Home.Test {
"use strict";
beforeEach(angular.mock.module("homeApp"));
describe("appInstanceService", () => {
let $httpBackend: angular.IHttpBackendService;
let $q: angular.IQService;
let service: Service.AppInstanceService;
beforeEach(
angular.mock.inject((
$http: angular.IHttpService,
_$q_: angular.IQService,
_$httpBackend_: angular.IHttpBackendService
) => {
$httpBackend = _$httpBackend_;
$q = _$q_;
service = new Service.AppInstanceService($http, $q, _, moment);
})
);
it("shoul pass", () => {
expect(true).toBe(true);
});
});
}
Here is my karma conf
module.exports = function(config) {
config.set({
// base path, that will be used to resolve files and exclude
basePath: '',
// testing framework to use (jasmine/mocha/qunit/...)
frameworks: ['jasmine'],
// list of files / patterns to load in the browser
files: [
'./bower_components/angular/angular.js',
'./bower_components/angular-animate/angular-animate.min.js',
'./bower_components/angular-bootstrap/ui-bootstrap-tpls.min.js',
'./bower_components/angular-mocks/angular-mocks.js',
'./bower_components/angular-sanitize/angular-sanitize.min.js',
'./bower_components/angular-translate/angular-translate.min.js',
'./bower_components/angular-ui-router/release/angular-ui-router.js',
'./bower_components/ui-select/dist/select.min.js',
'./bower_components/lucca-ui/dist/custom/lucca-ui-spe.js',
'./bower_components/moment/min/moment-with-locales.min.js',
'./bower_components/underscore/underscore-min.js',
'./dist/home.js',
'./tests/**/*.js',
],
preprocessors: {
'dist/home.js': ['coverage'],
},
// ngHtml2JsPreprocessor: {
// prependPrefix: '/web/Timmi.web/areas/timmi/'
// },
// list of files / patterns to exclude
exclude: [],
// web server port
port: 9876,
// 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: true,
// Continuous Integration mode
// if true, it capture browsers, run tests and exit
singleRun: false,
plugins: [
'karma-jasmine',
// 'karma-chrome-launcher',
// 'karma-firefox-launcher',
// 'karma-ie-launcher',
'karma-phantomjs-launcher',
'karma-junit-reporter',
'karma-coverage',
// 'karma-ng-html2js-preprocessor'
],
browsers: ['PhantomJS'],
reporters: ['progress'],
junitReporter: {
outputFile: 'test-karma-results.xml',
suite: 'Lucca',
useBrowserName: false
},
coverageReporter: {
type : 'json',
dir : 'coverage/',
subdir: '.',
file : 'coverage-final.json'
}
});
};
And here is the error message I get in the console
Some bower_components were missing under the files section of my karma conf ...
I have the next service "IrChartService":
public getDataAfterUpdate(entityId: number, timestamp: number) {
var deferred = this.$q.defer();
var requestUrl = this.IrChartData + '/datasequences/entities/' + entityId + '/ir?timestamp=' + timestamp;
this.$http.get(requestUrl).then((result) => {
deferred.resolve(result.data);
});
return deferred.promise;
}
That service is used in a controller.
Here I have the test file:
/* Test Code */
describe('IrChartService', function () {
var IrChartService, $httpBackend, $q, IrChartData;
beforeEach(function(){
angular.module('genscape.rt.irchart')
});
beforeEach(inject(function(_$httpBackend_, _IrChartService_, _$q_, _IrChartData_) {
IrChartService = _IrChartService_;
$httpBackend = _$httpBackend_;
$q = _$q_;
IrChartData = _IrChartData_;
}));
it('is defined', function () {
console.log('def');
expect(IrChartService).toBeDefined();
});
it('should call the backend testurl', function() {
var returnData = {
"ImagePath": "/20160406/167/167_20160406_065626.jpg",
"ConfidenceValue": 4
};
console.log('test');
//7. expectGET to make sure this is called once.
$httpBackend.expectGET("../mock/chartData.specs.json").respond(returnData);
$httpBackend.flush();
});
});
It return me errors like:
Error: [$injector:unpr] http://errors.angularjs.org/1.4.0-rc.2/$injector/unpr?p0=IrChartServiceProvider%20%3C-%20IrChartService
TypeError: Cannot read property 'expectGET' of undefined
Expected undefined to be defined.
Can you help me, please? Thanks!
Update:
// Karma configuration
// Generated on Wed May 20 2015 15:52:13 GMT-0400 (Eastern Daylight Time)
module.exports = function (config) {
config.set({
// base path that will be used to resolve all patterns (eg. files, exclude)
basePath: '',
// frameworks to use
// available frameworks: https://npmjs.org/browse/keyword/karma-adapter
frameworks: ['jasmine'],
plugins: [
'karma-chrome-launcher',
'karma-jasmine',
'karma-html-reporter',
'karma-ng-html2js-preprocessor'
],
// list of files / patterns to load in the browser
files: [
'Scripts/angular.min.js',
'Scripts/angular-mocks.js',
'Scripts/genscape.common.js',
'app/template.module.js',
'app/app.module.js',
'app/templates.js',
'app/app.widget.service.js',
'app/IRchart/IRchart.service.js',
'app/IRchart/IRchart.controller.js',
'app/IRchart/IRchart.directive.js',
'app/IRchart/IRchart-error.directive.js',
'app/IRchart/IRchart-popup/IRchart-popup.controller.js',
'app/IRchart/IRchart-player/IRchart-player.controller.js',
'app/IRchart/IRchart-player/IRchart-player.directive.js',
'test/specs/specs.js',
// fixtures
{ pattern: 'test/mock/*.json', watched: true, served: true, included: false }
],
preprocessors: {
'**/*.html': ['ng-html2js']
},
ngHtml2JsPreprocessor: {
// we want all templates to be loaded in the same module called 'templates'
moduleName: 'genscape.rt.irchart'
},
// list of files to exclude
exclude: [
],
// test results reporter to use
// possible values: 'dots', 'progress'
// available reporters: https://npmjs.org/browse/keyword/karma-reporter
reporters: ['progress', 'html'],
// web server port
port: 9876,
// enable / disable colors in the output (reporters and logs)
colors: true,
// level of logging
// possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
logLevel: config.LOG_INFO,
// enable / disable watching file and executing tests whenever any file changes
autoWatch: true,
// start these browsers
// available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
//browsers: ['Chrome'],
browsers: ['Chrome'],
// Continuous Integration mode
// if true, Karma captures browsers, runs the tests and exits
singleRun: false
});
};
I'm currently attempting to run tests using Karma, however I can't seem to load the Test file...
this is my file structure:
app
controllers
..
directives
..
..
test
customersControllerTest.js
karma.conf.js
test-main.js
..
this is my current karma.conf.js file:
module.exports = function(config) {
config.set({
// base path that will be used to resolve all patterns (eg. files, exclude)
basePath: '',
// frameworks to use
// available frameworks: https://npmjs.org/browse/keyword/karma-adapter
frameworks: ['jasmine', 'requirejs'],
// list of files / patterns to load in the browser
files: [
{pattern: './scripts/jquery.js', included: true},
{pattern: './scripts/angular.js', included: true},
{pattern: './scripts/angular-mocks.js', included: true},
'test-main.js',
{pattern: './test/*.js', included: false},
{pattern: './app/**/*.js', included: false},
],
// list of files to exclude
exclude: [
'**/*.css',
'**/bootstrap.js',
'**/routes.js',
'**/conf.js',
'**/app.js'
],
// preprocess matching files before serving them to the browser
// available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
preprocessors: {
},
// test results reporter to use
// possible values: 'dots', 'progress'
// available reporters: https://npmjs.org/browse/keyword/karma-reporter
reporters: ['progress'],
// web server port
port: 9876,
// enable / disable colors in the output (reporters and logs)
colors: true,
// level of logging
// possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
logLevel: config.LOG_DEBUG,
// enable / disable watching file and executing tests whenever any file changes
autoWatch: true,
// start these browsers
// available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
browsers: ['PhantomJS', 'Chrome', 'Firefox'],
plugins: [
'karma-*',
],
// Continuous Integration mode
// if true, Karma captures browsers, runs the tests and exits
singleRun: false
});
};
and my test-main.js file:
var testPaths = {
'customersControllersTest': '../test/customersControllersTest'
}, tests = Object.keys(window.__karma__.files).filter(function(file) {
return (/(spec|Test)\.js$/i.test(file));
}).map(function(test) {
var returnVal = false;
Object.keys(testPaths).map(function(path){
if(testPaths[path] === test.replace('/base', '..').replace('.js', '')) {
returnVal = path;
}
});
return returnVal;
});
require.config({
// Karma serves files under /base, which is the basePath from your config file
baseUrl: '/base/app',
paths: {
'jquery': '../scripts/jquery',
'angular': '../scripts/angular',
'angularMocks': '../scripts/angular-mocks',
// Modules
'servicesModule': './services/module',
'directivesModule': './directives/module',
'controllersModule': './controllers/module',
// Controllers
'testController': './controllers/testController',
'ordersController': './controllers/ordersController',
'allordersController': './controllers/allordersController',
'customersController': './controllers/customersController',
// Directives
'barChart': './directives/barsChartDirective',
'blueBarChart': './directives/blueBarsChartDirective',
// Services
'testService': './services/testService',
'routeResolver': './services/routeResolver',
'customersFactory': './services/customersFactory',
// Tests
'customersControllersTest': '../test/customersControllersTest'
},
// angular does not support AMD out of the box, put it in a shim
shim: {
'angular': {
deps: ['jquery'],
exports: 'angular'
},
'angularRoute': ['angular'],
'angularAnimate': ['angular'],
'angularMocks': ['angular']
},
// dynamically load all test files
deps: tests,
// we have to kickoff jasmine, as it is asynchronous
callback: window.__karma__.start()
});
and my customersControllersTest.js:
define('customersControllersTest', [], function() {
describe('test', function() {
console.log(this);
it('test1', function() {
expect('this').toEqual('this');
});
console.log(this);
});
});
By checking in Chrome's devtools, it gives an Error:
but when I open it:
This however might be completely unrelated, since I keep getting the following:
which, asides for saying it found no test, is yelling Error...
Any ideas on how I can tackle this?
One problem is the line:
callback: window.__karma__.start()
This calls start right away instead of passing it as callback. This line should have been
callback: window.__karma__.start
See karma-requirejs README.
I've created a simple test application that write hello.
The application is:
boot.js
require.config({
appDir: '',
baseUrl: '',
paths: {
angular: 'app/bower_components/angular/angular',
Controller: 'app/js/Controller'
},
shim: {
'angular': {'exports': 'angular'}
},
config: {
},
priority: [
"angular"
]
});
require(['app/js/Module'], function()
{
console.log("Loaded!");
});
Module.js:
(function(define) {
"use strict";
define(['angular', 'Controller'],
function(angular, NccController) {
var app, appName = 'myApp';
app = angular
.module(appName, [])
.controller('Controller', NccController);
angular.bootstrap(document.getElementsByTagName("body")[0], [appName]);
return app;
});
}(define));
Controller.js
(function(define) {
"use strict";
define([], function()
{
var NccController = function($scope)
{
$scope.message = "ciao"; //data to graph
};
return NccController;
});
}(define));
The content of karma.conf.js is:
module.exports = function(config) {
config.set({
// base path that will be used to resolve all patterns (eg. files, exclude)
basePath: '',
// frameworks to use
// available frameworks: https://npmjs.org/browse/keyword/karma-adapter
frameworks: ['jasmine', 'requirejs'],
// list of files / patterns to load in the browser
files: [
{pattern: 'public_html/app/bower_components/angular/angular.js', included: false}
'test-main.js',
{pattern: 'public_html/app/js/*.js', included: false},
{pattern: 'public_html/app/test/**/*Spec.js', included: false},
],
// list of files to exclude
exclude: [
'public_html/app/js/boot.js'
],
// preprocess matching files before serving them to the browser
// available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
preprocessors: {
},
// test results reporter to use
// possible values: 'dots', 'progress'
// available reporters: https://npmjs.org/browse/keyword/karma-reporter
reporters: ['progress'],
// web server port
port: 9876,
// enable / disable colors in the output (reporters and logs)
colors: true,
// level of logging
// possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
logLevel: config.LOG_INFO,
// enable / disable watching file and executing tests whenever any file changes
autoWatch: true,
// start these browsers
// available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
browsers: ['Chrome'],
// Continuous Integration mode
// if true, Karma captures browsers, runs the tests and exits
singleRun: false
});
};
the test-main.js is
var allTestFiles = [];
var TEST_REGEXP = /(spec|test)\.js$/i;
var pathToModule = function(path) {
return path.replace(/^\/base\//, '').replace(/\.js$/, '');
};
Object.keys(window.__karma__.files).forEach(function(file) {
if (TEST_REGEXP.test(file)) {
// Normalize paths to RequireJS module names.
allTestFiles.push(pathToModule(file));
}
});
require.config({
// Karma serves files under /base, which is the basePath from your config file
baseUrl: '/base',
paths: {
'angular': 'public_html/app/bower_components/angular/angular',
'Module': 'public_html/app/js/Module',
'Controller': 'public_html/app/js/Controller',
},
// dynamically load all test files
deps: allTestFiles,
// we have to kickoff jasmine, as it is asynchronous
callback: window.__karma__.start
});
the MainSpec.js is:
define(['Module','Controller'], function(angular,Module,Controller) {
describe('Controller', function(){
beforeEach(module('myApp'));
it('should print hello', inject(function($controller) {
var scope = {},
ctrl = $controller('Controller', {$scope:scope});
expect(scope.message).toBe('ciao');
}));
});
});
But when i run the test i obtain:
/usr/local/lib/node_modules/karma/bin/karma start
INFO [karma]: Karma v0.12.17 server started at http://localhost:9876/
INFO [launcher]: Starting browser Chrome
INFO [Chrome 36.0.1985 (Mac OS X 10.8.5)]: Connected on socket 14waTQA-kAa0VgYpvBBk with id 39770086
Chrome 36.0.1985 (Mac OS X 10.8.5) ERROR
Uncaught TypeError: Cannot read property 'module' of undefined
at /Users/daniele/Desktop/JARK/public_html/app/js/Module.js:8
What's wrong????
Thank you a lot.
Great tbranyen,
you've solved my great problem after 2 days of configuration. I post here all codes because I think that there're a lot of people that want to use angular/karma/RequireJs but have a lot of difficulty to setup all.
So boot.js, Module.js and controller.js are the same otherwise the file:
karma.conf.js is:
// Karma configuration
// Generated on Sat Jul 26 2014 18:36:34 GMT+0200 (CEST)
module.exports = function(config) {
config.set({
// base path that will be used to resolve all patterns (eg. files, exclude)
basePath: '',
// frameworks to use
// available frameworks: https://npmjs.org/browse/keyword/karma-adapter
frameworks: ['jasmine', 'requirejs'],
// list of files / patterns to load in the browser
files: [
{pattern: 'public_html/app/bower_components/angular/angular.js', included: false},
{pattern: 'public_html/app/bower_components/angular-mocks/angular-mocks.js', included: false},
{pattern: 'public_html/app/js/*.js', included: false},
{pattern: 'public_html/app/test/**/*Spec.js', included: false},
'test-main.js',
],
// list of files to exclude
exclude: [
'public_html/app/js/boot.js'
],
// preprocess matching files before serving them to the browser
// available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
preprocessors: {
},
// test results reporter to use
// possible values: 'dots', 'progress'
// available reporters: https://npmjs.org/browse/keyword/karma-reporter
reporters: ['progress'],
// web server port
port: 9876,
// enable / disable colors in the output (reporters and logs)
colors: true,
// level of logging
// possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
logLevel: config.LOG_INFO,
// enable / disable watching file and executing tests whenever any file changes
autoWatch: true,
// start these browsers
// available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
browsers: ['Chrome'],
// Continuous Integration mode
// if true, Karma captures browsers, runs the tests and exits
singleRun: false
});
};
test.main.js is:
var allTestFiles = [];
var TEST_REGEXP = /(spec|test)\.js$/i;
var pathToModule = function(path) {
return path.replace(/^\/base\//, '').replace(/\.js$/, '');
};
Object.keys(window.__karma__.files).forEach(function(file) {
if (TEST_REGEXP.test(file)) {
// Normalize paths to RequireJS module names.
allTestFiles.push(pathToModule(file));
}
});
require.config({
// Karma serves files under /base, which is the basePath from your config file
baseUrl: window.__karma__ ? "/base/" : "/",
paths: {
'angular': 'public_html/app/bower_components/angular/angular',
'angular-mocks': 'public_html/app/bower_components/angular-mocks/angular-mocks',
'Module': 'public_html/app/js/Module',
'Controller': 'public_html/app/js/Controller',
},
shim: {
'angular': {'exports': 'angular'},
'angular-mocks': ['angular']
},
});
require(['angular-mocks'], function() {
require(allTestFiles, window.__karma__.start);
});
and MainSpec.js is:
define(['angular','angular-mocks','Module','Controller'], function(angular,mocks,Module,Controller) {
describe('Controller', function(){
beforeEach(module('myApp'));
it('should print hello', inject(function($controller) {
var scope = {},
ctrl = $controller('Controller', {$scope:scope});
expect(scope.message).toBe('ciao');
}));
});
});
I hope that can help same people that want use it
Karma serves files under the /base/ root path, not /. You need to change your baseUrl property within the RequireJS configuration to be baseUrl: "/base/".
A simple way of handling this conditionally is:
baseUrl: window.__karma__ ? "/base/" : "/"
Edit:
I'm incorrect with the above, you have it configured correctly. The only other guess I have is that deps is loading your tests before the configuration has finished being set. Although you have mentioned that Angular loads 200 OK. My recommendation here would be to try extracting the test loading away from deps and instead break the configuration and loading into two different operations.
require.config({
"paths": { "angular": "<path/to/angular>" }
});
require(allTestFiles, function() {
window.__karma__.start();
});
I would also remove the callback from the karma Require configuration.
Edit 2:
Another recommendation would be to share your main application configuration so that you don't have to declare paths over again. An example of how this would look is:
https://gist.github.com/tbranyen/e37a7d888f7f90c25e63#file-config-js-L27-L28
Edit 3 (Hopefully last):
After debugging the project the error ended up being a missing Angular shim configuration in the test-main.js file.
Look at this project that uses requirejs and karma for angular js. Try and follow the set up. https://github.com/adikari/angular-seed
I am trying to configure my karma jasmine unit testing with requirejs. But each time i run it, i am getting the below error:
Chrome 34.0.1847 (Mac OS X 10.9.2) ERROR
Uncaught Error: Mismatched anonymous define() module: function (angular){
describe('Unit: Testing RequireJS', function(){
var ctrl;
var scope;
var rootScope;
beforeEach(angular.mock.module('wsaApp'));
beforeEach(angular.mock...<omitted>...ch
Below are differenr file:
spec file:
define(['angular'], function(angular){
describe('Unit: Testing RequireJS', function(){
var ctrl;
var scope;
var rootScope;
beforeEach(angular.mock.module('wsaApp'));
beforeEach(angular.mock.inject(function($rootScope){
scope = $rootScope.$new();
rootScope = $rootScope;
}));
});
});
main.js
require.config({
paths: {
/* ABC order */
'angular': 'vendor/angular/1.2.0/angular.min'
},
shim: {
'angular': { exports: 'angular' },
'app/controllers': { deps: ['angular'] }
}
});
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
});
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
});
}
i have tried different options mentioned in other threads, but nothing seems to work.
Finally i solved all the issues and was able to run the jasmine test successfully with requirejs configuration. I had top mention all the dependencies in the karma config and mark them as included: false exclusively so that they get loaded by requirejs through my test-config file.
files: [
{pattern: 'vendor/angular/1.2.1/angular.js', included: false},
{pattern: 'vendor/angular/1.2.1/angular-mocks.js', included: false},
{pattern: 'vendor/angular/1.2.1/angular-*.js', included: false},
{pattern: 'vendor/bootstrap/bootstrap-*.js', included: false},
{pattern: 'jquery-1.7.1.min.js', included: false},
{pattern: 'app/app.js', included: false},
{pattern: 'app/**/*.js', included: false},
{pattern: 'test/test-config.js', included: true}]
only the test-config is loaded through karma and all others to be included in the karma config but mark as false.
Also, i had to load the app.js in my spec file so that the modules and controllers get loaded:
define(['angular-mocks', 'jquery', 'app/app'], function(angularmocks, $, app){
describe.....
}
Since you're loading the specific .js files you need in your test-main.js with the paths: { } parameter, you don't have to explicitly list them in karma.config.js. Instead, you can just use your line { pattern: 'app/**/*.js', included: false }. All the lines before that are redundant. Just make sure you have the included: false modifier, otherwise Karma will load them in-line, and you'll get the Uncaught Error: Mismatched anonymous define() problem