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
Related
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.
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;
}));
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'm trying to set up WebStorm to develop AngularJS. I've followed the instructions from JetBrains and I'm trying to run the test from that tutorial.
describe('PhoneCat controllers', function() {
beforeEach(module('phonecatApp'));
describe('PhoneListCtrl', function(){
it('should create "phones" model with 3 phones', inject(function($controller) {
var scope = {},
ctrl = $controller('PhoneListCtrl', { $scope: scope });
expect(scope.phones.length).toBe(3);
}));
});
});
I'm getting the following error
"C:\Program Files (x86)\nodejs\node.exe" "C:\Program Files (x86)\JetBrains\WebStorm 7.0.3\plugins\js-karma\js_reporter\karma-intellij\lib\intellijRunner.js" --karmaPackageDir=C:\Users\L\node_modules\karma --serverPort=9876 --urlRoot=/
Testing started at 21:02 ...
ReferenceError: module is not defined
at null.<anonymous> (C:/Users/L/WebstormProjects/AngularJS/test/unit/ControllerTests.js:4:16)
at C:/Users/L/WebstormProjects/AngularJS/test/unit/ControllerTests.js:3:1
Process finished with exit code 0
My directory layout is
test/unit/ControllerTest.js
test/karma.conf.js
karma.conf.js below
// Karma configuration
// Generated on Sun Feb 16 2014 20:49:06 GMT+0000 (GMT Standard Time)
module.exports = function(config) {
config.set({
// base path, that will be used to resolve files and exclude
basePath: '',
// frameworks to use
frameworks: ['jasmine'],
// list of files / patterns to load in the browser
files: [
{pattern: '*.js', included: true},
{pattern: 'unit/*.js', included: true}
],
// list of files to exclude
exclude: [
],
// test results reporter to use
// possible values: 'dots', 'progress', 'junit', 'growl', 'coverage'
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, currently available:
// - Chrome
// - ChromeCanary
// - Firefox
// - Opera (has to be installed with `npm install karma-opera-launcher`)
// - Safari (only Mac; has to be installed with `npm install karma-safari-launcher`)
// - PhantomJS
// - IE (only Windows; has to be installed with `npm install karma-ie-launcher`)
browsers: ['Chrome'],
// If browser does not capture in given timeout [ms], kill it
captureTimeout: 60000,
// Continuous Integration mode
// if true, it capture browsers, run tests and exit
singleRun: false
});
};
angular-mocks.js is missing
See http://devnet.jetbrains.com/thread/452824?tstart=0
in karma.conf.js should change to :
basePath: './',
$files: [
{pattern: './*.js', included: true},
{pattern: './unit/*.js', included: true}
],