AngularJS with Karma: $controller not defined error - javascript

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',
...
],

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/Jasmine tests are failing due to: TypeError: MysmartdevicesCtrl is undefined

My angularjs tests are all failing due to the controller being undefined. I tried several different solutions yet nothing is working. I've added every js file i thought was needed in karma, from the looks of it I don't think the beforeEach(inject... function is getting called or if it is then something isnt getting set right. I added print statements along the way but nothing ever gets printed in the beforeEach(inject... function call.
Error Log:
Firefox 49.0.0 (Ubuntu 0.0.0) Controller: RegisteruserCtrl should attach a list of awesomeThings to the scope FAILED
minErr/<#bower_components/angular/angular.js:68:12
loadModules/<#bower_components/angular/angular.js:4640:15
forEach#bower_components/angular/angular.js:321:11
loadModules#bower_components/angular/angular.js:4601:5
createInjector#bower_components/angular/angular.js:4523:19
workFn#bower_components/angular-mocks/angular-mocks.js:3074:44
[3]</ContextKarma/this.loaded#http://localhost:9876/context.js:151:7
TypeError: RegisteruserCtrl is undefined in test/spec/controllers/registeruser.js (line 21)
#test/spec/controllers/registeruser.js:21:5
[3]</ContextKarma/this.loaded#http://localhost:9876/context.js:151:7
Firefox 49.0.0 (Ubuntu 0.0.0): Executed 3 of 3 (3 FAILED) ERROR (0.17 secs / 0.09 secs)
registerCtrl.js Spec:
'use strict';
describe('Controller: RegisteruserCtrl', function () {
// load the controller's module
beforeEach(module('clientApp'));
var RegisteruserCtrl,
scope;
// Initialize the controller and a mock scope
beforeEach(inject(function ($controller, $rootScope) {
scope = $rootScope.$new();
RegisteruserCtrl = $controller('RegisteruserCtrl', {
$scope: scope
// place here mocked dependencies
});
}));
it('should attach a list of awesomeThings to the scope', function () {
expect(RegisteruserCtrl.awesomeThings.length).toBe(3);
});
});
karma.conf.js
// Karma configuration
// Generated on Tue Oct 11 2016 18:25:32 GMT-0500 (CDT)
"use strict";
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-route/angular-route.js',
'bower_components/angular-mocks/angular-mocks.js',
'app/**/app.js',
'app/Common/*.js',
'app/scripts/controllers/*.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: {},
plugins: [
'karma-firefox-launcher',
'karma-chrome-launcher',
'karma-jasmine',
],
// 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: ['Firefox'],
// Continuous Integration mode
// if true, Karma captures browsers, runs the tests and exits
singleRun: true
});
};
Using the minimatch pattern (/**/*):
'app/**/app.js',
'app/Common/*.js',
caused me a lot of trouble. Instead of doing that way explicitly write the name of the controller (or file) you need. For example:
app/Common/RegisteruserCtrl.js
Here's an example that works for me:
files: [
'./node_modules/angular/angular.js', // angular
'./node_modules/angular-mocks/angular-mocks.js', // angular-mocks
'./app/views/js/controllers/sugestionController.js'
],

Karma testing with typescript and angular 2 is throwing Typeerror for "System.config"

I'm super new to testing, I'm using angular 2 as a new beginning to learning.
ERRROR:
INFO [Chrome 42.0.2311 (Mac OS X 10.9.3)]: Connected on socket xo5ufjmFKLGc5QSuAAAB with id 34336816
WARN [web-server]: 404: /base/jspm_packages/es6-module-loader.js
ERROR [karma]: Uncaught TypeError: System.config is not a function
at http://localhost:9876/base/js/angular.js?4c894ae47e8d04bb01965dbf22fa08aed20f0eb2:25575
ERROR [karma]: Uncaught ReferenceError: require is not defined
at http://localhost:9876/base/app/app.js?8a00e7f6717b2dd7118e800d05625a443a4b2065:13
QUESTION:
How can I get remedy the TypeError and uncaught Reference Error, so my main.spec.js can pass?
Karma.conf
// Karma configuration
// Generated on Mon May 18 2015 18:17:07 GMT-0700 (PDT)
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: [
'app/app.js',
'tests/*.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
});
};
tests/main.spec.js:
import Foo from '../app/app.js';
describe('ES6 Foo', function () {
let foo;
beforeEach(()=>{
foo = new Foo();
});
it('should call foo.thing and test default value', function(){
expect(foo.thing).toEqual(0);
});
});
index.html
<html>
<head>
<script src="./js/traceur.js"></script>
<script src="./jspm_packages/system.js"></script>
<script src="./js/angular2.js"></script>
</head>
<body>
<main-app></main-app>
<script>
System.import('app/app');
</script>
</body>
</html>
app.ts
/// <reference path="../typings/angular2/angular2"/>
import {bootstrap, Component, View} from 'angular2/angular2'
#Component({
selector:'main-app',
injectables: [
]
})
#View({
templateUrl: 'app/main.html',
})
class MainApp {
thing;
constructor(){
this.thing = 0
}
add(){
this.thing++;
}
subtract(){
this.thing--;
}
}
bootstrap(MainApp);
Your problem is directly linked to this bug
https://github.com/angular/angular/issues/2049
The problem is that the module loader is being loaded from the wrong URL (hence the 404 error you are seeing) and that makes System not be available.
The Angular2 team uses Protractor with Webdriver. You should be able to get Chrome to work in that configuration.

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

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.

Categories