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.
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.
This question already has answers here:
Getting "Mismatched anonymous define() module..." when I try running tests
(2 answers)
Closed 5 years ago.
I am trying to run unit test cases for my controllers, I have tried the following but getting the below error, please let me know to run this test successfully. Thanks in advance.
spec.js:
describe('MainCtrl', function() {
beforeEach(module('app-module'));
var $controller;
beforeEach(inject(function(_$controller_){
$controller = _$controller_;
}));
describe('$scope.titleofapp', function() {
var $scope, controller;
beforeEach(function() {
$scope = {};
controller = $controller('MainCtrl', { $scope: $scope });
});
it('sets the title of app to "app-module" module', function() {
$scope.titleofapp();
expect($scope.title).toEqual('My Test App !');
});
});
});
app.js:
define(['angular', './app-module'], function(angular, appModule) {
'use strict';
return appModule.controller('MainCtrl', ['$http', '$q', 'appService', '$stateParams', function($http, $q, $stateParams, appService){
$scope.titleofapp = function(){
$scope.title = 'My Test App !';}
}]);
});
Below is my karma.conf.js file configuration:
karma.conf.js:
module.exports = function(config) {
config.set({
basePath: '',
frameworks: ['jasmine','requirejs'],
files: [
'node_modules/requirejs/require.js',
'node_modules/karma-requirejs/lib/adapter.js',
'node_modules/angular/angular.js',
'node_modules/angular-mocks/angular-mocks.js',
'public/app/app.js',
'public/tests/spec.js'
],
exclude: [
],
plugins: [
'karma-requirejs',
'karma-chrome-launcher',
'karma-jasmine'
],
preprocessors: {
},
reporters: ['progress'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ['Chrome'],
singleRun: false,
concurrency: Infinity
})
}
I have configured requirejs like above and getting the below error now:
Error:
Uncaught Error: Mismatched anonymous define() module: function (angular, appModule) {
'use strict';
return appModule.controller('MainCtrl', ['$http', '$q', 'appService', '$stateParams', function($http, $q, $stateParams, appService){
$scope.titleofapp = function(){
$scope.title = 'My Test App !';}
}]);
}
http://requirejs.org/docs/errors.html#mismatch
at node_modules/requirejs/require.js:165
Here is your karma.conf.js file I've edited to make possible run with RequireJS. Comments styled as // -- mostly (except when trailing) the stuff that I commented out, and styled as /* */ -- are real comments about what's the purpose of specific line presence or absence. I hope all that commenting will help to understand what's going on.
module.exports = function(config) {
config.set({
basePath: '',
frameworks: ['jasmine','requirejs'],
files: [
/* not needed because you've told to use requirejs higher in frameworks */
// 'node_modules/requirejs/require.js',
/* i assume this one in no need in your case but could be yes */
// 'node_modules/karma-requirejs/lib/adapter.js',
/* as far as i understand angular.js is amd loadable so don't load it directly */
// 'node_modules/angular/angular.js',
/* i am not sure about this one and how it should be launched so commented it out for now */
// 'node_modules/angular-mocks/angular-mocks.js',
/* will be loaded by tests*/
// 'public/app/app.js',
/* tests should not be loaded directly eigther */
// 'public/tests/spec.js'
/* now configure karma with what will be servable */
{pattern: 'node_modules/**/*.js', included: false}, // all stuff from what npm installed
{pattern: 'src/**/*.js', included: false}, // your source filed
{pattern: 'tests/**/*Test.js', included: false}, // your tests or specs
/* this is the only file to be loaded directly */
'tests/test-main.js' // karma will load this file and it will do all the stuff
],
exclude: [
],
/* karma will load all sibling npm modules with name karma-* so these lines not needed i believe */
// plugins: [
// 'karma-requirejs',
// 'karma-chrome-launcher',
// 'karma-jasmine'
// ],
preprocessors: {
},
reporters: ['progress'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ['Chrome'],
singleRun: false,
concurrency: Infinity
})
}
Then here I made a sample code for main-test.js file.
var allTestFiles = [];
var TEST_REGEXP = /base\/tests\/.*(spec|test)\.js$/i;
// Get a list of all the test files to include
/* as far as i remember window.__karma__.files contains array of all servable files */
Object.keys(window.__karma__.files).forEach(function (file) {
//console.log('original path', file);
if (TEST_REGEXP.test(file)) {
/* below i commented out file path modification suggested at http://karma-runner.github.io/1.0/plus/requirejs.html
* personally i never needed that. Your case might be different so you can play around with this part
*/
var normalizedTestModule = file;//'/base/' + file.replace(/^\/base\/|\.js$/g, '')
//console.log('normalized path', normalizedTestModule);
allTestFiles.push(normalizedTestModule);
}
});
//console.log(allTestFiles); // list all test filed that will be run
/* now confifure requirejs so it could do the job
* for more details please visit http://requirejs.org/docs/api.html#config
*/
require.config({
// Karma serves files under /base, which is the basePath from your config file
/* i prefer this to be default */
baseUrl: '/base/src',
paths: {
/* could be this to do stuff like
* define(['node_modules/cool-module/module.js], function(Module){
*
* });
*/
node_modules: '/base/node_modules',
/* below is just examples that what it could be if you needed those */
// jquery: '/base/node_modules/jquery/dist/jquery',
// underscore: '/base/node_modules/underscore/underscore',
// backbone: '/base/node_modules/backbone/backbone',
// text: '/base/node_modules/requirejs-text/text',
// templates: '/base/src/templates'
},
/* Dynamically load all test files
* An array of dependencies to load. Useful when require is defined as a
* config object before require.js is loaded, and you want to specify
* dependencies to load as soon as require() is defined. Using deps
* is just like doing a require([]) call, but done as soon as the loader
* has processed the configuration. It does not block any other require()
* calls from starting their requests for modules, it is just a way to
* specify some modules to load asynchronously as part of a config block.
* (http://requirejs.org/docs/api.html#config-deps)
*/
deps: allTestFiles,
/* A function to execute after deps have been loaded. Useful when require
* is defined as a config object before require.js is loaded, and you want
* to specify a function to require after the configuration's deps array
* has been loaded.
* http://requirejs.org/docs/api.html#config-callback
* Could be as simple as
* callback: window.__karma__.start
* but i do it via additional wrapper so i can require something specific
* for the whole test suite (like jasmine-jquery), you will the sample below
*/
callback: startTestWithJasmineJquery
});
function startTestWithJasmineJquery(){
require(['node_modules/jasmine-jquery/lib/jasmine-jquery'], function(){
/* now jasmine-jquery is loaded and its features are available
* so we can window.__karma__.start -- it will actually run tests
*/
window.__karma__.start();
});
}
Please note that all config options assume folder and some specific files structure as:
node_modules/
src/
tests/
test-main.js
karma-conf.js
Please also note again that this is very basic config I've provided and there might be some specific stuff relative to angular or your project logic and needs and thus there might be some (or many) changes to be made.
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...
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'