Karma + RequireJS + AngularJS, shimmed scripts not loading in spec - angularjs

While using Karma + Jasmine + RequireJS + AngularJS, I'm unable to load any of my shimmed scripts, for example angular-mocks, into the test specs. The file seem to be served all right, just doesn't work in the spec.
UPDATE Angular is global, and the corresponding shim doesn't affect it.
In Karma.conf.js, I'm including angular-mocks to be loaded by RequireJS:
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: 'node_modules/angular-mocks/angular-mocks.js', included: false},
...
'test/euro-2016/main-test.js'
],
// list of files to exclude
exclude: [
'main/main-euro-2016.js'
],
// preprocess matching files before serving them to the browser
// available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
preprocessors: {
'../../*.html': ['ng-html2js']
},
// 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'],
// Continuous Integration mode
// if true, Karma captures browsers, runs the tests and exits
singleRun: false,
// Concurrency level
// how many browser should be started simultaneous
concurrency: Infinity
})
};
The RequireJS shim in the Karma main file main-test.js:
var tests = [];
for (var file in window.__karma__.files) {
if (window.__karma__.files.hasOwnProperty(file)) {
if (/Spec\.js$/.test(file)) {
tests.push(file);
}
}
}
requirejs.config({
// Karma serves files from '/base'
baseUrl: "/base",
paths: {
"angular": "vendor/angular/angular",
"angularMocks": "node_modules/angular-mocks/angular-mocks",
"jquery": "vendor/jquery/jquery.min",
...
},
shim: {
"angular": {
exports: "angular",
deps: ['jquery']
},
"angularMocks": {
exports: "angularMocks",
deps: ['angular']
},
...
},
// ask Require.js to load these files (all our tests)
deps: tests,
// start test run, once Require.js is done
callback: window.__karma__.start
});
The spec file:
define(['angular', 'modules/euro-2016/app', 'angularMocks'], function(angular, app, mocks){
console.log("ANGULAR", angular); // ok
console.log("APP", app); // ok
console.log("MOCKS", mocks); // undefined
})

Looking at the source code that is installed by installing the NPM package angular-mocks, specifically the file node_modules/angular-mocks/angular-mocks.js, here is what I see:
There is no mention of angularMocks anywhere in that code, therefore exporting angularMocks cannot work.
Conversely, the plugin installs itself as angular.mock. Early in the file there is the line:
angular.mock = {};
And then everything is added to angular.mock.
So you can remove your exports and access the plugin through angular.mock. This should work:
define(['angular', 'modules/euro-2016/app', 'angularMocks'], function(angular, app){
console.log("ANGULAR", angular);
console.log("APP", app);
console.log("MOCKS", angular.mock);
});
If you must have an exports for some reason (for instance if you use enforceDefine, which requires that all shim have exports values) you could set it to angular.mock.

Related

How to import typescript files with karma-systemjs?

Background
I'm trying to set up a test runner for an Angular 1x app, but I'm not able to get Karma to work with Systemjs and Typescript.
The tests are written in Typescript, and we use Systemjs to import files that use ES6 modules. Most files do not use ES6 modules.
Instead of using a karma prepreocessor like karma-typescript, I'm trying to use Systemjs to transpile my Typescript. Is that the wrong way to go? It doesn't seem like any transpiling is happening!
The error
When I run karma start, the script fails on the import of a typescript namspace:
import core = myApp.core;
Chrome 52.0.2743 (Windows 7 0.0.0) ERROR
Error: (SystemJS) SyntaxError: Unexpected token import
Evaluating app/scripts/site/core/components/settingsMenu/settingsMenu.spec.ts
Error loading app/scripts/site/core/components/settingsMenu/settingsMenu.spec.ts
Here is my karma.conf.js file, based on this example.
// Karma configuration
// Generated on Thurs Apr 13 2017
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: ['systemjs', 'jasmine'],
systemjs: {
configFile: 'config.js',
config: {
paths: {
'systemjs': 'app/vendor/systemjs/system.src.js',
'system-polyfills': 'app/vendor/systemjs/system-polyfills.src.js',
'typescript': '/node_modules/typescript/lib/typescript.js'
},
packages: {
'app': {
defaultExtension: 'ts'
}
},
transpiler: 'typescript'
},
serveFiles: [
'app/scripts/**/*!(spec).ts'
]
},
// list of files / patterns to load in the browser
files: [
{ pattern: 'app/scripts/**/*.spec.ts' }
],
// list of files to exclude
exclude: [],
// 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
});
};
systemjs config:
System.config({
baseURL: './',
defaultJSExtensions: true
});
Try adding the transpiler property in your systemjs config (config.js):
System.config({
baseURL: './',
defaultJSExtensions: true,
transpiler: 'typescript'
});

Jasmine Inject not working

So I have an angular 1.5 app that I compile with Typescript and then bundle it via Browserify.
Now when I want to test it with Karma and Jasmine I get an error as soon as I want to inject a service (it works fine in the browser with strict-di enabled).
Does someone see where the error is?
CacheServiceTest.ts
import {CacheService} from "../../../app/services/CacheService";
import {Application} from "../../../app/Application";
describe("AppComponent", () => {
beforeEach(() => {
angular.mock.module(Application.name);
});
it("should contain CacheService", () => {
inject((CacheService:CacheService) => {
console.log(CacheService);
});
});
});
Karma config
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", "browserify"],
// list of files / patterns to load in the browser
files: [
"node_modules/angular/angular.js",
"node_modules/angular-mocks/angular-mocks.js",
"node_modules/ngLeague/dist/ngLeague.js",
"node_modules/angular-localforage/dist/angular-localForage.js",
"app/**/*.ts",
"tests/unit/**/*.ts",
// JSON fixture
{
pattern: "tests/fixtures/**/*.json",
watched: true,
served: true,
included: false
}
],
// list of files to exclude
exclude: [],
// preprocess matching files before serving them to the browser
// available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
preprocessors: {
"app/**/*.ts": ["browserify", "ng-annotate"],
"tests/unit/**/*.ts": ["browserify", "ng-annotate"],
"dist/ngCache.js": "coverage"
},
// Browserify config
browserify: {
debug: true,
plugin: [
["tsify", {target: "ES5"}]
]
},
// test results reporter to use
// possible values: "dots", "progress"
// available reporters: https://npmjs.org/browse/keyword/karma-reporter
reporters: ["progress", "coverage"],
coverageReporter: {
type : "html",
dir : "tests/coverage/"
},
// 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: ["PhantomJS"],
// Continuous Integration mode
// if true, Karma captures browsers, runs the tests and exits
singleRun: false
});
};
Error
forEach#/home/kme/Documents/ngCache/node_modules/angular/angular.js:322:24
loadModules#/home/kme/Documents/ngCache/node_modules/angular/angular.js:4548:12
createInjector#/home/kme/Documents/ngCache/node_modules/angular/angular.js:4470:30
workFn#/home/kme/Documents/ngCache/node_modules/angular-mocks/angular-mocks.js:2954:60
inject#/home/kme/Documents/ngCache/node_modules/angular-mocks/angular-mocks.js:2934:46
/tmp/fe42636aeb0f927c8dcd9afa7c80f051.browserify:16447:15 <- tests/unit/services/CacheServiceTest.ts:14:15
/home/kme/Documents/ngCache/node_modules/angular/angular.js:4588:53

Why do I get a 404 message from Karma webserver?

At the moment, I'm trying to setup a demo project with Node/AngularJs/JSPM with ES6 transpiler Babel and Karma.
The serving part is working. I need to improve it later but the first 'hello world' from angular is working.
I'd like to add Karma to run unit tests for the angular app. But I'm getting a 404 warning for jspm_packages, see screenshot below.
My test is not running because it will always fail. My test file looks like this (no angular specific part in there yet):
// HomeController.spec.js
import 'angular-mocks';
describe('Test suite for HomeController', function() {
it('dummy test', function() {
expect(true).toBe(true); // will not fail
});
});
Not sure what's wrong and I've tried many things with-out success maybe I did something wrong. But here is what I've tried in the Karma config:
Tried many different path setting because I think it's an issue with the path
Used proxies
Browserify and Bablify to transpile the sources
JSPM plugin to load the dependencies for testing
You can find the code I'm currently working on here at bitbucket.
The directory structure of my app looks like this:
Here is a screenshot of Karma:
Here is my current Karma config 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: ['jspm', 'jasmine'],
// list of files / patterns to load in the browser
files: [
//'client/test-unit/**/*.test.js'
],
jspm: {
paths: {
// '*': 'client/app/**/*.js'
},
// Edit this to your needs
// config: 'client/app/jspm.config.js',
// Edit this to your needs
loadFiles: ['client/test-unit/**/*.spec.js'],
serveFiles: ['client/app/**/*.js', 'client/app/**/*.css', 'client/app/**/*.html']
},
proxies: {
// '/assets/jspm_packages/': '/client/app/assets/jspm_packages/'
},
plugins:[
'karma-jasmine',
'karma-coverage',
'karma-jspm',
'karma-chrome-launcher'
],
// list of files to exclude
exclude: [
],
// preprocess matching files before serving them to the browser
// available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
preprocessors: {
// 'client/app/**/*.js': ['browserify'],
// 'client/test-unit/**/*.js': ['browserify']
},
/*browserify: {
debug: true,
transform: [ 'babelify' ]
},*/
// babelPreprocessor: {
// options: {
// sourceMap: 'inline'
// },
// filename: function (file) {
// return file.originalPath.replace(/\.js$/, '.es5.js');
// },
// sourceFileName: function (file) {
// return file.originalPath;
// }
// },
// 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
});
};
I think I've found a fix to my problem.
I had to setup some proxies to make it work.
Also the change of the log level to logLevel: config.LOG_DEBUG for debugging my issue was helpful because then you'll see more details to the problem.
Another problem was that the test file was not transpiled before execution. That was because the preprocessors for transpiling were not setup correctly.
And the packages path inside of the jspm object is required too to make it work.
It's still pretty hard to understand and I'm not sure if there's an easier way to do it.
Anyway the following karma.config is working for me:
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: ['jspm', 'jasmine'],
// list of files / patterns to load in the browser
files: [
//'client/test-unit/**/*.test.js'
],
proxies: {
'/base/app/': '/base/client/app/',
'/base/assets/jspm_packages/': '/base/client/app/assets/jspm_packages/'
},
jspm: {
// Edit this to your needs
config: 'client/app/jspm.config.js',
// Edit this to your needs
loadFiles: ['client/test-unit/**/*.spec.js'],
serveFiles: ['client/app/**/*.js'],
packages: "client/app/assets/jspm_packages/"
},
plugins:[
'karma-jasmine',
'karma-coverage',
'karma-jspm',
'karma-chrome-launcher'
],
// list of files to exclude
exclude: [
],
// preprocess matching files before serving them to the browser
// available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
preprocessors: {
'test-unit/**/*.js': ['babel', 'coverage']
// 'client/app/**/*.js': ['browserify'],
// 'client/test-unit/**/*.js': ['browserify']
},
/*browserify: {
debug: true,
transform: [ 'babelify' ]
},*/
// babelPreprocessor: {
// options: {
// sourceMap: 'inline'
// },
// filename: function (file) {
// return file.originalPath.replace(/\.js$/, '.es5.js');
// },
// sourceFileName: function (file) {
// return file.originalPath;
// }
// },
// 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, //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
});
};
And my test file looks like this:
// HomeController.spec.js
import 'app/app';
import 'angular-mocks';
describe('Test suite for HomeController', function() {
// var homeController;
beforeEach(function() {
module('myApp');
// inject(function($controller) {
// console.log('inject called', $controller);
// //controller = $controller;
// homeController = $controller('homeController');
// });
});
it('should say "Hello World"', inject(function($controller) {
var homeController = $controller('homeController');
// console.log(homeController, angular.mocks);
expect(homeController.hello).toEqual('Hello world from ES6 HomeController.'); // will not fail
})
);
});

AngularJS, RequireJS, Karma - Test File not loading

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.

angular - requireJs - karma

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

Resources