Afternoon all,
I have a MEAN stack app that I am developing tests for. The Angular code is written using ES6 so I have been trying to configure Karma and SystemJS with Babel as the transpiler to run my tests. Currently, when I karma start karma.conf.js the browser fires up, hangs—as in I cannot click debug or anything else—, and then the browser closes with the console error:
Uncaught TypeError: Cannot set property 'mock' of undefined.
The last line before this is DEBUG [web-server]: serving (cached): ( ... )
My current application structure works like this:
I have all of my module imported into one file app.js where they are injected into my app module:
import HomeController from './components/home/home.js';
import HomeService from './services/homeservice.js';
import HomeDirective from './directives/homedirective.js';
import DifferentController from './components/different/different.js';
// ### Filters
import slugifyFilter from './filters/slugify.js';
var moduleName = 'app';
angular.module(moduleName, ['ngNewRouter', 'ngMock', 'ngAnimate', 'ui.bootstrap', 'slugifyFilter'])
.config(['$componentLoaderProvider', SetTemplatesPath])
.controller('AppController', ['$router', AppController]);
function SetTemplatesPath ($componentLoaderProvider){
$componentLoaderProvider.setTemplateMapping(name => `components/${name}/${name}.html`);
}
function AppController ($router) {
$router.config([
// Component is just a template + controller
// in 'components' folder
{ path: '/', redirectTo: '/home' },
{ path: '/home', component: 'home' },
{ path: '/different/:id', component: 'different' }
]);
}
export default moduleName;
I use manual Angular bootstrapping in my index.html file as so:
import { default as AppModule } from './app.js';
angular.bootstrap(document, [ AppModule ]);
try {
$(document.body).attr("ng-app", "app");
} catch(e){};
I have Karma and SystemJS configured as so:
// Karma configuration
// Generated on Tue Jul 07 2015 19:56:15 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: './',
files : [],
// frameworks to use
// available frameworks: https://npmjs.org/browse/keyword/karma-adapter
frameworks: ['systemjs', 'jasmine'],
plugins : ['karma-systemjs', 'karma-jasmine', 'karma-chrome-launcher',
'karma-firefox-launcher', 'karma-ie-launcher' ],
// preprocess matching files before serving them to the browser
// available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
preprocessors: { "**/*.html": ['ngbootstrapfix'] },
systemjs : {
// Path to SystemJS config file
//configFile : 'public/system.conf.js',
// File patterns for application code, dependencies, and test suites
files : [
'public/bower_components/jquery/dist/jquery.js',
'public/bower_components/angular/angular.js',
'public/bower_components/angular-mocks/angular-mocks.js',
'public/bower_components/angular-animate/angular-animate.js',
'public/bower_components/angular-bootstrap/ui-bootstrap-tpls.js',
'public/bower_components/angular-new-router/dist/router.es5.js',
'public/bower_components/angular-messages/angular-messages.js',
'public/**/*.js'
],
// SystemJS configuration specifically for tests, added after your config file.
// Good for adding test libraries and mock modules
config: {
baseURL : '/',
// Set path for third-party libraries as modules
paths : {
'jquery': 'public/bower_components/jquery/dist/jquery.js',
'angular-mocks': 'public/bower_components/angular-mocks/angular-mocks.js',
'angular' : 'public/bower_components/angular/angular.js',
'angular-animate' : 'public/bower_components/angular-animate/angular-animate.js',
'ui-bootstrap' : 'public/bower_components/angular-bootstrap/ui-bootstrap-tpls.js',
'router' : 'public/bower_components/angular-new-router/dist/router.es5.js',
'angular-messages' : 'public/bower_components/angular-messages/angular-messages.js',
'babel': 'node_modules/babel-core/browser.js',
'es6-module-loader': 'node_modules/es6-module-loader/dist/es6-module-loader.js',
'systemjs': 'node_modules/systemjs/dist/system.js',
'system-polyfills': 'node_modules/systemjs/dist/system-polyfills.js'
},
transpiler: 'babel'
},
// Specify the suffix used for test suite file names. Defaults to .test.js, .spec.js, _test.js, and _spec.js
testFileSuffix: '-spec.js'
},
// 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: ['Chrome'],
// Continuous Integration mode
// if true, Karma captures browsers, runs the tests and exits
singleRun: true
});
};
I have a filter here that I am trying to test:
let moduleName = 'slugifyFilter';
angular.module(moduleName, [])
.filter('slugify', () => {
return (input) => {
input = input || '';
return input.replace(/ /g, '-').toLowerCase();
};
});
export default moduleName;
And my test file:
import 'angular-mocks';
import '../bootstrap.js';
describe('slugify filter', function() {
beforeEach(function() {
angular.mock.module('app');
});
beforeEach(angular.mock.inject(function(_$filter_) {
var $filter = _$filter_;
}));
it('returns a slug when given a string', function() {
var slugify = $filter('slugify');
expect(slugify('Home Component 3')).toContain('home-component-3');
});
});
Yet whenever I try to run the tests I get the error described above. What really bothers me is that the browser freezes before the window says 'browser executing.' Any help would be really appreciated, I really want to write some unit tests for my code!
Add these files to the karma.files array:
'public/bower_components/jquery/dist/jquery.js',
'public/bower_components/angular-mocks/angular-mocks.js',
'public/bower_components/angular/angular.js'
Related
I've finished to implement my web site with AngularJS and now, I must make my unit test to verify the correct functioning of my functions.
I was looking for a lot of tutorial on internet but apparently, my application structure doesn't allow testing with karma and jasmin.
Let me explain, I got a site web with just one single page HTML which is linked with one controller (a file .js) I've never installed Angular with NPM but I've imported it with:
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular.min.js"></script>
And I load my controller with:
<script src="main.js"></script>
and some other imported script.
I would like to try my controller with unit tests, so I've created a package.json file and installed karma, jasmine, and karma-cli with npm.
I've make a folder called "Tests" and created a test.js file:
describe("App",() =>{ //Describe object type
beforeEach(module('App')); //Load module
describe('Ctrl',()=>{
var Ctrl;
beforeEach(inject( ($injector)=>{ //instantiate controller using $controller service
$rootScope = $injector.get('$rootScope');
$controller = $injector.get('$controller');
$scope = $rootScope.$new();
}));
beforeEach(inject(($controller)=>{
Ctrl = $controller("Ctrl");
}));
it("Should say hello",()=>{
expect(Ctrl.msg).toBe("Hello");
})
})
})
But when I use:
karma start
it's doesn't detect my controller.
Here is my console output:
Here is my karma.conf.js:
// Karma configuration
// Generated on Thu Jun 14 2018 16:51:15 GMT+0200 (Paris, Madrid (heure d’été))
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'],
// list of files / patterns to load in the browser
files: [ 'Scripts/angular.js','Scripts/angular-mocks.js','main.js','Tests/*.js'
],
// list of files / patterns 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,
// Concurrency level
// how many browser should be started simultaneous
concurrency: Infinity
})
}
And how i declare my controller :
var app = angular.module('App', ['ngMaterial', 'ngMessages'])
app.controller('Ctrl', ['$rootScope', '$scope','$http','$timeout','$mdDialog','Global', 'projects', 'screens', 'users', 'licenses', function($rootScope, $scope, $http, $timeout, $mdDialog,Global, projects, screens, users, licenses) {
...
}
Here is my tree folder :
-Root
|---node_modules
|---Tests
| |---test.js
|---Scripts
|---index.html
|---main.js <--- controller of my index.html
|---style.css
|---someFactory.js
I don't think I'm doing it in the right way. Please, explain me how to do it.
I have an Angular Application using Jasmine and Karma for testing.
This is my testing class:
var data = require('./user.mock.js');
describe('Service: UserService', function () {
var ServerUrl;
var httpBackend;
var userService;
beforeEach(angular.mock.module('myModule'));
beforeEach(angular.mock.inject(function (_userService_, $httpBackend, _ServerUrl_) {
userService = _userService_;
httpBackend = $httpBackend;
ServerUrl = _ServerUrl_;
}));
describe('when get the active users from backend', function () {
// given
beforeEach(function () {
httpBackend
.whenGET(ServerUrl + '/users')
.respond(angular.copy(data.activeUsers));
});
it('should return the list of active users', function () {
var expectedUsers = angular.copy(data.activeUsers);
expectedUsers[0].profilePicture = ServerUrl + '/pictures/' + expectedUsers[0].id + '/small/show';
expectedUsers[1].profilePicture = ServerUrl + '/pictures/' + expectedUsers[1].id + '/small/show';
userService
.listUsers()
.then(function(users) {
expect(users).toEqual(expectedUsers);
});
httpBackend.flush();
});
});
And this is my karma conf:
// Karma configuration
// Generated on Tue May 19 2015 15:02:17 GMT+0100 (WEST)
module.exports = function(config) {
config.set({
// base path that will be used to resolve all patterns (eg. files, exclude)
basePath: '',
// testing framework to use (jasmine/mocha/qunit/...)
frameworks: [ 'jasmine', 'browserify'],
// list of files / patterns to load in the browser
files: [
'http://maps.googleapis.com/maps/api/js?sensor=false&language=en',
// bower:js
"bower_components/jquery/dist/jquery.js",
"bower_components/angular/angular.js",
"bower_components/angular-mocks/angular-mocks.js",
"bower_components/angular-animate/angular-animate.js",
"bower_components/angular-bootstrap/ui-bootstrap-tpls.js",
"bower_components/angular-cookies/angular-cookies.js",
"bower_components/angular-gettext/dist/angular-gettext.js",
"bower_components/angular-http-auth/src/http-auth-interceptor.js",
"bower_components/angular-notify/dist/angular-notify.js",
"bower_components/angular-resource/angular-resource.js",
"bower_components/angular-route/angular-route.js",
"bower_components/angular-sanitize/angular-sanitize.js",
"bower_components/angular-touch/angular-touch.js",
"bower_components/angular-ui-utils/ui-utils.js",
"bower_components/angular-ui-map/ui-map.js",
"bower_components/bootstrap-sass/assets/javascripts/bootstrap.js",
"bower_components/bootstrap-select/dist/js/bootstrap-select.js",
"bower_components/event-signal/dist/event-signal.min.js",
"bower_components/google-map-infobubble/src/infobubble.js",
"bower_components/moment/moment.js",
"bower_components/ng-file-upload/ng-file-upload.js",
"bower_components/ng-file-upload-shim/ng-file-upload-shim.js",
"bower_components/angularUtils-pagination/dirPagination.js",
// endbower
'src/app/**/*.js',
'src/app/views/**/*.html',
'src/test/**/*.js'
],
// list of files / patterns to exclude
exclude: [
],
// preprocess matching files before serving them to the browser
// available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
preprocessors: {
'**/*.html': ['ng-html2js'],
'src/**/*.js': ['browserify']
},
ngHtml2JsPreprocessor: {
// strip this from the file path
stripPrefix: 'src/',
// prepend this to the
// setting this option will create only a single module that contains templates
// from all the files, so you can load them all with module('foo')
moduleName: 'templatesForTest'
},
//
// // test results reporter to use
// // possible values: 'dots', 'progress', 'spec'
// // available reporters: https://npmjs.org/browse/keyword/karma-reporter
// reporters: ['spec'],
//
//
// // 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
});
};
When I run karma test from the command line, the services injected do not get recognized. I am suspecting that the inject function is not being called in the beforeEach method, but I am not sure. I am getting undefined in the tests, as if the variable never got any value.
workFn#/Users/brunosiqueira/WebstormProjects/copcast-admin/bower_components/angular-mocks/angular-mocks.js:2507:60
TypeError: undefined is not an object (evaluating 'httpBackend
.whenGET') in /var/folders/pz/wmyql55d43lchz7p3jv_jmr40000gn/T/3081904ada407f95301fa9ebb665e38e.browserify (line 5994)
/var/folders/pz/wmyql55d43lchz7p3jv_jmr40000gn/T/3081904ada407f95301fa9ebb665e38e.browserify:5994:18
TypeError: undefined is not an object (evaluating 'userService
.getUserVideos') in /var/folders/pz/wmyql55d43lchz7p3jv_jmr40000gn/T/3081904ada407f95301fa9ebb665e38e.browserify (line 6012)
/var/folders/pz/wmyql55d43lchz7p3jv_jmr40000gn/T/3081904ada407f95301fa9ebb665e38e.browserify:6012:18
Can you guys help me?
Two things I remember:
The order of the JS files has to be right in the config files
The usage seems grossly right and is this. Just check if this makes a
difference :
beforeEach(inject(function($controller, $rootScope, _myService_){
scope = $rootScope.$new();
myServiceSvc = _myService_;
firstCtrl = $controller("firstCtrl",{
$scope: scope,
myService: myServiceSvc
});
}));
karma.conf
files: [
'index.html',
'lib/angular.min.js',
'lib/angular-ui-router.min.js',
'lib/angular-mocks/angular-mocks.js',
'lib/app.js',
'tests/controller/basics.js'
],
In the end it just a stupid error (as most of them are).
Using git bisect, I was able to find the commit where the tests stopped working.
In that commit, I saw that I added the ng-jwplayer dependency to the project. The library requires a javascript call before it the html file.
'https://content.jwplatform.com/libraries/XXXXXX.js',
That url was missing in the karma.conf files array. It was generating an error:
files: [
'http://maps.googleapis.com/maps/api/js?sensor=false&language=en',
'https://content.jwplatform.com/libraries/XXXXXX.js',
// bower:js
'bower_components/jquery/dist/jquery.js',
'bower_components/angular/angular.js',
'bower_components/angular-animate/angular-animate.js',
'bower_components/angular-bootstrap/ui-bootstrap-tpls.js',
'bower_components/angular-cookies/angular-cookies.js',
'bower_components/angular-gettext/dist/angular-gettext.js',
'bower_components/angular-http-auth/src/http-auth-interceptor.js',
'bower_components/angular-notify/dist/angular-notify.js',
'bower_components/angular-resource/angular-resource.js',
'bower_components/angular-route/angular-route.js',
'bower_components/angular-sanitize/angular-sanitize.js',
'bower_components/angular-touch/angular-touch.js',
'bower_components/angular-mocks/angular-mocks.js',
'bower_components/angular-ui-utils/ui-utils.js',
'bower_components/angular-ui-map/ui-map.js',
'bower_components/bootstrap-sass/assets/javascripts/bootstrap.js',
'bower_components/bootstrap-select/dist/js/bootstrap-select.js',
'bower_components/event-signal/dist/event-signal.min.js',
'bower_components/google-map-infobubble/src/infobubble.js',
'bower_components/moment/moment.js',
'bower_components/ng-jwplayer/jwplayer.min.js',
'bower_components/ng-file-upload/ng-file-upload.js',
'bower_components/ng-file-upload-shim/ng-file-upload-shim.js',
'bower_components/angularUtils-pagination/dirPagination.js',
// endbower
'src/app/**/*.js',
'src/app/views/**/*.html',
'src/test/**/*.js'
],
With the url included, the files work well. This was another case of misleading error message.
I am trying to do testing using jasmine .When I run this command karma start karma.conf.js it give me this error.
Chrome 47.0.2526 (Windows 7 0.0.0) Firstcontroller Initialization title should be naveen FAILED
Error: [$injector:modulerr] Failed to instantiate module app due to:
Error: [$injector:nomod] Module 'app' is not available! You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the depend
encies as the second argument.
http://errors.angularjs.org/1.4.8/$injector/nomod?p0=app
at D:/Webapplication/karmaTest/bower_components/angular/angular.js:68:12
at D:/Webapplication/karmaTest/bower_components/angular/angular.js:2005:17
at ensure (D:/Webapplication/karmaTest/bower_components/angular/angular.js:1929:38)
at module (D:/Webapplication/karmaTest/bower_components/angular/angular.js:2003:14)
at D:/Webapplication/karmaTest/bower_components/angular/angular.js:4435:22
at forEach (D:/Webapplication/karmaTest/bower_components/angular/angular.js:340:20)
at loadModules (D:/Webapplication/karmaTest/bower_components/angular/angular.js:4419:5)
at Object.createInjector [as injector] (D:/Webapplication/karmaTest/bower_components/angular/angular.js:4344:11)
at Object.workFn (D:/Webapplication/karmaTest/bower_components/angular-mocks/angular-mocks.js:2428:52)
at window.inject.angular.mock.inject (D:/Webapplication/karmaTest/bower_components/angular-mocks/angular-mocks.js:2411:37)
I install karma , karma-jasmine ,karma-chrome launcher ..When I run simple test like expect(true).toBeTruthy it works fine.But when I am trying to test my controller .it gives me above error .
here is my controller
//(function () {
// 'use strict';
//
// angular.module('app',[]).controller('FirstController',FirstController);
//
// FirstController.$inject=['$scope']
//
// function FirstController($scope){
// $scope.title='naveen';
// }
//
//})();
angular.module('app',[]).controller('FirstController',FirstController);
FirstController.$inject=['$scope'];
function FirstController($scope){
$scope.title='naveen';
}
here is my test-spec.js file
describe('Firstcontroller', function () {
var $rootScope,
$scope,
controller;
beforeEach(function () {
module('app');
inject(function ($injector) {
$rootScope = $injector.get('$rootScope');
$scope=$rootScope.$new();
console.log('==========================')
controller=$injector.get('$controller')('FirstController',{$scope:$scope});
})
})
describe('Initialization',function(){
it('title should be naveen',function(){
expect($scope.title).toEqual('naveen')
})
})
})
it give be above error why ?
I include the package in karma.config file
karma.config file
// Karma configuration
// Generated on Tue Dec 08 2015 18:55:16 GMT+0530 (India 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'],
// list of files / patterns to load in the browser
files: [
'bower_components/angular/angular.js',
'bower_components/angular-mocks/angular-mocks.js',
'bower_components/angular-resource/angular-resource.js',
'app/**/.js',
'test/**/*.js'
],
// 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,
// Concurrency level
// how many browser should be started simultanous
concurrency: Infinity
})
}
update
I insert my js file inside the app directory when I change this 'app/**/.js' to 'app/*.js' it works fine ..why it works ?
Module 'app' is not available! You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the dependencies as the second argument.
The module in your Angular code is 'apps' not 'app'.
Fix the spelling mistake and it should work.
Okay, so I have a seed setup and I have Jasmin Running (Thank you so much SoEzPz for the help).
it appears my spec's won't run, I tried and isolated spec and it ran with no issue but when I try to write one on a controller it errors.
here is the controller.
//This is the about function that is used in the About Module.
'use strict';
app.controller('AboutController',// jshint ignore:line
['$scope',
function ($scope) {
$scope.message = 'This is the about page message from the controller';
}]);
a very basic controller
here is my test
'use strict';
describe('Controller: com/modules/AboutController', function() {
beforeEach(module('app'));
var AboutController,
scope;
beforeEach(inject(function ($rootScope, $controller) {
scope = $rootScope.$new();
AboutController = $controller('AboutController', {
$scope: scope
});
}));
it('It should show the page message', function () {
expect(scope.greeting).toEqual("This is the about page message from the controller");
});
});
The spec returns this error
ReferenceError: module is not defined
at Suite.<anonymous> (http://localhost:8888/com/modules/about/aboutController_spec.js:5:16)
at addSpecsToSuite (http://localhost:8888/:801:25)
at Env.describe (http://localhost:8888/:771:7)
at jasmineInterface.describe (http://localhost:8888/:3277:18)
at http://localhost:8888/com/modules/about/aboutController_spec.js:3:1
am I missing something or is my spec written wrong ?
I am including the ngmock here is my Karma.conf file
// Karma configuration
// Generated on Tue Jul 28 2015 11:28:22 GMT-0400 (EDT)
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'],
// list of files / patterns to load in the browser
files: [
'../src/lib/js/angular/angular.min.js',
'../src/lib/js/angular/angular-mocks.js',
'../src/com/**/*.js',
'../src/com/**/*_spec.js'
],
// 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: ['PhantomJS'],
// Continuous Integration mode
// if true, Karma captures browsers, runs the tests and exits
singleRun: false
})
}
This was definitely deceptive, after playing around with the specs (thinking that the issue was in the actual specifications ) I found a test that ran fine, but still my other specs would not run, so what I did was I went back and took a hard look at my karma.conf file and while looking through some of the other examples I found I wasn't including enough in the way of bower components. so I added some more IE resources, cookies ect and low and behold all tests passed .
here is what I added under files for those who might be having the same issue
'bower_components/angular/angular.js',
'bower_components/angular-route/angular-route.js',
'bower_components/angular-mocks/angular-mocks.js',
'bower_components/angular-resource/angular-resource.js',
'bower_components/angular-cookies/angular-cookies.js',
'bower_components/angular-sanitize/angular-sanitize.js',
'../src/com/**/*.js',
'../src/com/**/*_spec.js'
I have an Angular app with a simple karma test and a very simple configuration using requirejs and Angular 1.2.28. My test is ok.
/**
* Created by jose on 7/12/2015.
*/
/*global module, inject */
define(['home', 'angularMocks','ngStorage'], function(app) {
'use strict';
describe('homeController', function () {
var scope, $location, createController;
beforeEach(module('homeApp'));
beforeEach(inject(function ($rootScope, $controller, _$location_) {
$location = _$location_;
scope = $rootScope.$new();
createController = function () {
return $controller('homeController', {
'$scope': scope
});
};
}));
it('should have message', function () {
var controller = createController();
$location.path('/');
expect($location.path()).toBe('/');
expect(scope.message).toEqual('This is Add new order screen');
});
});
});
My module:
/**
* Created by jose on 7/12/2015.
*/
'use strict';
define(['angular', 'angularRoute'], function(angular) {
var app = angular.module('homeApp', ['ngRoute']);
app.config(['$routeProvider',
function ($routeProvider) {
$routeProvider.
when('/', {
templateUrl: 'partials/home.html',
controller: 'homeController'
})
.when('/404', {
templateUrl: 'partials/404.html',
})
.otherwise({
redirectTo: '/404'
});
}
]);
app.controller('homeController', function ($scope) {
$scope.message = 'This is Add new order screen';
});
return app;
});
Unfortunately, when I try to add ngStorage as a dependency for this module, it cannot works anymore. Even try to add ngStorage to my karma configuration raise an error like this:
Error: Mismatched anonymous define() module: function (app) {
It only happens when I try to use ngStorage, when I just comment it into my karma.conf file error disappears and everything works fine...
In case of not being possible using ngStorage with Karma there are another alternatives for ngStorage? thanks
karma.conf
// Karma configuration
// Generated on Mon Jul 13 2015 09:49:28 GMT-0300 (Hora est. Sudamérica Pacífico)
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: [
'test-main.js',
'bower_components/angular/angular.js',
'bower_components/angular-mocks/angular-mocks.js',
'bower_components/angular-route/angular-route.js',
'bower_components/ngstorage/ngStorage.js',
{pattern: 'javascripts/*.js', included: false},
{pattern: 'test/**/*Spec.js', included: false}
],
// list of files to exclude
exclude: [
'javascripts/config.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'],
// Continuous Integration mode
// if true, Karma captures browsers, runs the tests and exits
singleRun: false
});
};
Project is at github: https://github.com/jbarros35/node/tree/master/angulartemplate
kind regards.
It appears as though you are not the only one receiving errors trying to use Karma and ngStorage together. The guys at Karma have made some of their code available to help resolve the issue. You can check it out here:
https://github.com/gsklee/ngStorage/issues/117
If you look at the code of ngStorage you'll see that it calls define. So it is a proper AMD modules. Each AMD module you use in a Karma setup must be loaded with included: False in files:
{ pattern: 'bower_components/ngstorage/ngStorage.js', included: False }
Otherwise, Karma will load it with a script element, and you will get the error you got.
It's because of the async load feature of require js. Errors can be solved by this way
Go to the test-main.js.
add shim there in this way
shim:{
'yourJsModule':{
deps:['angular','yourApp']
}
}
replace "yourJsModule" with the your angular file you intend to test and the 'yourApp' with your angular module file...