Karma gives me errors when running tests (related to backbone.js)? - javascript

My error is related to backbone.js 'undefined' is not an object (evaluating '_.each') it's pointing to line 227 which is inside my test.js script which was compiled by browserify.
This line is a built-in block within backbone, so the actual issue can't be within that line obviously.
So my setup... I am testing a simple module here, it's Inside ./client/src/views/.
// intro.js
var Backbone = require('backbone');
module.exports = IntroView = Backbone.View.extend({
el: '.intro',
initialize: function() {
this.render();
},
render: function() {
this.$el.height($(window).height() - 10);
}
});
Then I have the actual test module inside ./client/spec/views/
// intro.test.js
var IntroView = require('../../src/views/intro.js'),
$ = require('jquery');
describe('view:intro', function() {
var introView = new IntroView();
it('just testing if I can get a success', function() {
expect(1 + 2).toEqual(3);
});
it('should render the view', function() {
introView.render();
});
});
Okay so I run gulp browserify to compile the script like this
gulp.task('browserify:tests', function() {
return gulp.src('./client/spec/views/intro.test.js')
.pipe(tasks.browserify({
transform: ['hbsfy', 'browserify-shim']
}))
.pipe(tasks.concat('tests.js'))
.pipe(gulp.dest('./test'));
});
Then inside my karma.config.js
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: [
'./test/tests.js',
],
// 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: false,
// 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: ['PhantomJS'],
// 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: true
});
};
Lastly I run karma start in the command line. So I hope I am using karma the right way, I think I am but if I want to test my code which uses backbone I need to get past this hump.
So my question is what am I doing wrong, why is the error occurring within the backbone.js code? Also am I doing it the right way?

I had the same error, but it was caused by using modules maping in my requirejs config. I've solved it by using paths instead (i've overwrite my browser config).
Your problem is most likely that you didn't have requirejs config. See requirejs config page for further instructions.

Related

Require is not defined, angularDragula is not defined - how to fix karma config problems?

Just beginning on testing with Jamsine and Karma. I tried to follow the official AngularJS docs as well as couple of other articles to set up my config and start testing. I am getting this require is not defined and angularDragula is not defined errors when I run karma start. I am trying to an AngularJS controller here. Here is my karma config file:
module.exports = function(config) {
config.set({
// base path that will be used to resolve all patterns (eg. files, exclude)
basePath: '',
// frameworks to use
// available frameworks: https://npmjs.org/browse/keyword/karma-adapter
frameworks: ['jasmine','browserify'],
plugins: ['karma-jasmine','karma-chrome-launcher','karma-browserify'],
// list of files / patterns to load in the browser
files: [
'public/assets/bower_components/angular/angular.min.js',
'node_modules/angular-mocks/angular-mocks.js',
'public/assets/bower_components/angular-dragula/angular-dragula.js',
'public/app/controllers/testController.js',
'public/app/app.js',
'public/app/controllers/testController.spec.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: {
'public/*.js': ['browserify']
},
// 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
})
}
I tried searching for the require error and found that browserify is required when karma tests in the browser. I installed it and added to the config file (preprocessors). But still doesn't help.
Here is my spec:
describe('Controller Test', function(){
beforeEach(module('App'));
var $controller;
beforeEach(inject(function(_$controller_){
$controller = _$controller_;
}));
describe('$scope.testVar', function(){
var $scope, controller;
beforeEach(function(){
$scope = {};
controller = $controller('testController', {$scope : $scope});
it('checks value for testVar', function(){
expect($scope.testVar).toEqual('hey');
})
})
})
})
I still get this error:
Chrome 70.0.3538 (Linux 0.0.0) ERROR
{
"message": "An error was thrown in afterAll\nUncaught ReferenceError: require is not defined\nUncaught ReferenceError: angularDragula is not defined",
"str": "An error was thrown in afterAll\nUncaught ReferenceError: require is not defined\nUncaught ReferenceError: angularDragula is not defined"
}
Chrome 70.0.3538 (Linux 0.0.0): Executed 0 of 0 ERROR (0.005 secs / 0 secs)
Can someone help me out here?

ReferenceError: browser is not defined - Using Karma and Jasmine

I am getting ReferenceError: browser is not defined when trying to set up some basic tests with Jasmine and Karma.
Here is my Karma config file
// Karma configuration
// Generated on Wed Mar 08 2017 13:29:09 GMT+0000 (GMT)
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: [
'./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: ['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 then I have one test file called loginSpec.js shown here:
describe('login page', function() {
beforeEach(function(){
browser().navigateTo('/');
});
it('should have the correct title', function() {
expect(browser.getTitle()).toEqual('Title');
});
});
Whenever I run the test in the Karma tool window I get the following error:
ReferenceError: browser is not defined
at Object.<anonymous> (spec/loginSpec.js:11:9)
ReferenceError: browser is not defined
at Object.<anonymous> (spec/loginSpec.js:15:16)
I don't understand why browser is suddenly not defined as I had tests working before setting up Karma (using WebdriverIO and selenium-standalone). These tests were written in the same way and there were no errors regarding browser
I have also researched and found that a lot of other people have had the same issue, but they are having it because of issues with Angular, which i am not using?
Using karma,jasmine there is no handler/object as browser available like WebdriverIO and selenium-standalone.
If you are looking to write a unit test case using jasmine to test the route, it can be done via injecting $location service of angular as below:
describe('login page', function() {
beforeEach(angular.mock.inject((_$rootScope_, _$location_) => {
_$location_.path('/');
_$rootScope_.$digest();
}));
it('should have the correct title', function() {
expect(browser.getTitle()).toEqual('Title');
});
});

karma testing - services injection error

i have inhereted a angular project that uses npm, grunt, bower ... and karma + jasmin.
i have been asked to setup some tests for the project using karma and jasmin.
karma has already been setup in the project but never used.
when i run 'grunt test' i get injection errors on all of the services, like the following.
Error: [$injector:unpr] Unknown provider: excelparserserviceProvider <- excelparserservice
http://errors.angularjs.org/1.2.6/$injector/unprp0=excelparserserviceProvider%20%3C-%20excelparserservice
there is already a karma.conf.js looking like this.
i havent changed anything in the karma.conf file, except adding some of the libaries that used in the project into the list under Files: [].
module.exports = function(config) {
config.set({
// base path, that will be used to resolve files and exclude
basePath: '',
// testing framework to use (jasmine/mocha/qunit/...)
frameworks: ['jasmine'],
// list of files / patterns to load in the browser
files: [
'app/bower_components/angular/angular.js',
'app/bower_components/angular-mocks/angular-mocks.js',
'app/bower_components/angular-resource/angular-resource.js',
'app/bower_components/angular-cookies/angular-cookies.js',
'app/bower_components/angular-sanitize/angular-sanitize.js',
'app/bower_components/angular-route/angular-route.js',
// i manually added the ones from here
'app/bower_components/jquery/dist/jquery.js',
'app/bower_components/geocoder-js/dist/geocoder.js',
'app/bower_components/js-xlsx/dist/xlsx.core.min.js',
'app/bower_components/angular-bootstrap/ui-bootstrap-tpls.js',
'app/bower_components/d3/d3.js',
'app/bower_components/angular-file-upload/angular-file-upload.js',
// to here.
'app/scripts/*.js',
'app/scripts/**/*.js',
'test/mock/**/*.js',
'test/spec/**/*.js'
],
// list of files / patterns to exclude
exclude: [],
// web server port
port: 8080,
// 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'],
// Continuous Integration mode
// if true, it capture browsers, run tests and exit
singleRun: false
});
};
the paths,
'app/scripts/*.js' --> leads to app.js and a config.js
'app/scripts/**/*.js' -->leads to all services controllers and directives
'test/mock/**/*.js' --> is non existent
'test/spec/**/*.js'--> contains all the test files
there are test files corresponding to every part of the applikation. Which i have been told has been auto generated. So i find it weird if they should contain the error. but the one related to the excpelparserservice injection error is.
'use strict';
describe('Service: excelparserservice', function () {
// load the service's module
beforeEach(module('batchUploadApp'));
// instantiate service
var Excelparserservice;
beforeEach(inject(function (_excelparserservice_) {
Excelparserservice = _excelparserservice_;
}));
it('should do something', function () {
expect(!!Excelparserservice).toBe(true);
});
});
the declaration of the service looks like this.
'use strict';
angular.module('batchUploadApp')
.service('ExcelParserService',
function ExcelParserService($q, ExcelvalidationService, GeoLocationService) {
the application in general works.
hope i my explication is usefull :)
thank you.
You define and register your service like this:
angular.module('batchUploadApp').service('ExcelParserService', ...
meaning that you register it under the name ExcelParserService. On the other hand, when you try to inject the service into you test, you use its name in lowercase:
beforeEach(inject(function (_excelparserservice_) {
Both names must match, thus the solution is to change the name of the parameter:
beforeEach(inject(function (_ExcelParserService_) {

AngularJS with Karma: $controller not defined error

I'm very new to testing but thought it was a good idea to start out some testing with this project. When I run grunt karma:watch I get the error with this configuration files.
I have a config file containing:
module.exports = function(config) {
config.set({
basePath: '../..',
// testing framework to use (jasmine/mocha/qunit/...)
frameworks: ['jasmine'],
// list of files / patterns to load in the browser
files: [
'src/js/vendors/angular.js',
'src/js/vendors/angular-mock.js',
'src/js/app/navigation/*js',
'src/**/*.js',
'src/js/vendors/*.js',
'src/test/unit/**/*.spec.js',
'dist/templates/**/*.js'
],
// list of files / patterns to exclude
exclude: [],
// web server port
port: 8080,
// 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'],
// Continuous Integration mode
// if true, it capture browsers, run tests and exit
singleRun: false
});
};
And my unit test looks like this:
describe('NavCtrl', function(){
var scope;
beforeEach(angular.mock.module('integra'));
beforeEach(angular.mock.inject(function($rootScope,$controller){
scope = $rootScope.$new();
$controller('NavCtrl', {$scope: scope});
}));
$scope.type = {
language: "English",
i18n: "en_EN"
};
$scope.option(type);
expect($scope.type.i18n).toEqual('en_EN');
})
This is the error:
Chrome 33.0.1750 (Linux) ERROR
Uncaught ReferenceError: $controller is not defined
at ~/Project/theApp/src/test/unit/app/navigation/NavCtrl.spec.js:2
Why isn't the $controller defined? Where should I define it? The controller I wan't to test is located in /src/js/navigation/NavCtrl.js
Error in path to controller's file in the configuration file.
Used
files: [
...,
'src/js/app/navigation/*js',
...
],
Instead of
files: [
...,
'src/js/app/navigation/*.js',
...
],

Mocha - Chai Karma "suite is not defined"

I'm quite new to jscript tdd and got a problem, hope someone can show me what I'm doing worng.
Running the Tests in a browser (via HTML File) everything works fine. running them through node and karma i got the following exception
I want to use Mocha and Chai within karma in node.js host.
I installed via npm install [...] --save-dev mocha and karma-mocha
I've a testlibrary like this
suite('first suite', function () {
test('SuccessTest', function () {
expect(1).to.equal(1);
});
test('FailTest', function () {
expect(1).to.equal(2);
});
});
in node i used karma init to create the config file in which i set frameworks to
frameworks: ['mocha','chai'],
now when I run karma it got this error
"suite is not defined"
I assumed that declaring mocha and chai as frameworks this should have worked?
I also installed in node the karma-mocha and karma-chai plugins.
What do I wrong and what do I have to do ?
where the whole karma config file
// Karma configuration
// Generated on Mon Sep 23 2013 17:24:19 GMT+0200 (Mitteleuropäische Sommerzeit)
module.exports = function(config) {
config.set({
// base path, that will be used to resolve files and exclude
basePath: '',
// frameworks to use
frameworks: ['mocha','chai'],
// list of files / patterns to load in the browser
files: [
'tests.js'
],
// 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
// - Safari (only Mac)
// - PhantomJS
// - IE (only Windows)
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
});
};
I also tried to add mocha.js and chai.js to the file load list but this didn't help
files: [
'mocha.js',
'chai.js',
'tests.js'
],
When I change tests to jasmine it works.
This is because there is no "chai" framework/plugin for Karma, but I think it's a good idea to have one.
You need to do this in some of your included files, in order to use "tdd" mocha style ("bdd" is the default one):
// in config-mocha.js
window.mocha.setup({ui: 'tdd'});
You need to load "chai" manually:
module.exports = function(config) {
config.set({
files: [
'path/to/chai.js',
'config-mocha.js',
// .. your source and test files
]
});
};

Categories