Karma: cannot read property 'style' of undefined - angularjs

I'm trying to do unit tests on my Angularjs code using karma.
This is my conf 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'],
// list of files / patterns to load in the browser
files: [
'http://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js',
'https://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js',
'https://code.angularjs.org/1.2.26/angular-mocks.js',
'test/unit/**/*.js',
'js/app.js',
'js/controllers/AffairesCtrl.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_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: false
});
};
I'm testing a function which has the following code:
document.getElementById('case').style.display="none";
When I run the test, I get this error:
TypeError: Cannot read property 'style' of undefined
But, if I replace the javascript code with jQuery code:
$("#case").css("display","none");
Then, the test is a success and the previous error disappear.
Do you know why I get this error?
Thank you!

Likely because your document has no element with an id of "case".
See the documentation on getElementById
jQuery on the other hand does not return null if no elements exist as mentioned in this stackoverflow post. Therefore no error.

Related

How to import typescript files with karma-systemjs?

Background
I'm trying to set up a test runner for an Angular 1x app, but I'm not able to get Karma to work with Systemjs and Typescript.
The tests are written in Typescript, and we use Systemjs to import files that use ES6 modules. Most files do not use ES6 modules.
Instead of using a karma prepreocessor like karma-typescript, I'm trying to use Systemjs to transpile my Typescript. Is that the wrong way to go? It doesn't seem like any transpiling is happening!
The error
When I run karma start, the script fails on the import of a typescript namspace:
import core = myApp.core;
Chrome 52.0.2743 (Windows 7 0.0.0) ERROR
Error: (SystemJS) SyntaxError: Unexpected token import
Evaluating app/scripts/site/core/components/settingsMenu/settingsMenu.spec.ts
Error loading app/scripts/site/core/components/settingsMenu/settingsMenu.spec.ts
Here is my karma.conf.js file, based on this example.
// Karma configuration
// Generated on Thurs Apr 13 2017
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: ['systemjs', 'jasmine'],
systemjs: {
configFile: 'config.js',
config: {
paths: {
'systemjs': 'app/vendor/systemjs/system.src.js',
'system-polyfills': 'app/vendor/systemjs/system-polyfills.src.js',
'typescript': '/node_modules/typescript/lib/typescript.js'
},
packages: {
'app': {
defaultExtension: 'ts'
}
},
transpiler: 'typescript'
},
serveFiles: [
'app/scripts/**/*!(spec).ts'
]
},
// list of files / patterns to load in the browser
files: [
{ pattern: 'app/scripts/**/*.spec.ts' }
],
// 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
});
};
systemjs config:
System.config({
baseURL: './',
defaultJSExtensions: true
});
Try adding the transpiler property in your systemjs config (config.js):
System.config({
baseURL: './',
defaultJSExtensions: true,
transpiler: 'typescript'
});

Jasmine Inject not working

So I have an angular 1.5 app that I compile with Typescript and then bundle it via Browserify.
Now when I want to test it with Karma and Jasmine I get an error as soon as I want to inject a service (it works fine in the browser with strict-di enabled).
Does someone see where the error is?
CacheServiceTest.ts
import {CacheService} from "../../../app/services/CacheService";
import {Application} from "../../../app/Application";
describe("AppComponent", () => {
beforeEach(() => {
angular.mock.module(Application.name);
});
it("should contain CacheService", () => {
inject((CacheService:CacheService) => {
console.log(CacheService);
});
});
});
Karma config
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"],
// list of files / patterns to load in the browser
files: [
"node_modules/angular/angular.js",
"node_modules/angular-mocks/angular-mocks.js",
"node_modules/ngLeague/dist/ngLeague.js",
"node_modules/angular-localforage/dist/angular-localForage.js",
"app/**/*.ts",
"tests/unit/**/*.ts",
// JSON fixture
{
pattern: "tests/fixtures/**/*.json",
watched: true,
served: true,
included: false
}
],
// 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: {
"app/**/*.ts": ["browserify", "ng-annotate"],
"tests/unit/**/*.ts": ["browserify", "ng-annotate"],
"dist/ngCache.js": "coverage"
},
// Browserify config
browserify: {
debug: true,
plugin: [
["tsify", {target: "ES5"}]
]
},
// test results reporter to use
// possible values: "dots", "progress"
// available reporters: https://npmjs.org/browse/keyword/karma-reporter
reporters: ["progress", "coverage"],
coverageReporter: {
type : "html",
dir : "tests/coverage/"
},
// 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
});
};
Error
forEach#/home/kme/Documents/ngCache/node_modules/angular/angular.js:322:24
loadModules#/home/kme/Documents/ngCache/node_modules/angular/angular.js:4548:12
createInjector#/home/kme/Documents/ngCache/node_modules/angular/angular.js:4470:30
workFn#/home/kme/Documents/ngCache/node_modules/angular-mocks/angular-mocks.js:2954:60
inject#/home/kme/Documents/ngCache/node_modules/angular-mocks/angular-mocks.js:2934:46
/tmp/fe42636aeb0f927c8dcd9afa7c80f051.browserify:16447:15 <- tests/unit/services/CacheServiceTest.ts:14:15
/home/kme/Documents/ngCache/node_modules/angular/angular.js:4588:53

Grunt Test Task

i have set up a grunt task for running test using Karma and Jasmine for testing an AngularJS framework!
For some reasons same configurations i have used for other projects fails for this one. here is the error message am getting:
forEach#/home/username/sw-projects/project/bower_components/angular/angular.js:340:24
loadModules#/home/username/sw-projects/project/van/bower_components/angular/angular.js:4419:12
createInjector#/home/username/sw-projects/project//bower_components/angular/angular.js:4344:22
workFn#/home/jofomah/sw-projects/van/bower_components/angular-mocks/angular-mocks.js:2409:60
/home/username/sw-projects/project/bower_components/angular/angular.js:4459:53
Expected undefined to be defined.
/home/username/sw-projects/project/app/common/utility/utility.service.spec.js:16:34
My Karma config:
// Karma configuration
// Generated on Fri Mar 18 2016 14:24:49 GMT+0100 (WAT)
var bowerJS = require('wiredep')({
dependencies: true,
exclude: [/jasmine$/],
devDependencies: true
}).js;
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: bowerJS.concat([
'.tmp/*.js',
// 'config.js',
// 'country-config.js',
'app/routes.js',
'app/app.js',
'app/common/rest/rest-client.js',
'app/common/utility/utility.service.js',
'app/common/settings/settings.js',
'app/common/brand/brand.directive.js',
'app/common/footer/footer.directive.js',
'app/common/week-picker/week-picker.directive.js',
'app/common/state-selector/state-selector.directive.js',
'app/common/loading-blanket/loading-blanket.directive.js',
'app/common/transform-listener/transform-listener.module.js',
'app/common/transform-listener/transform-listener.service.js',
'app/common/transform-listener/transform-listener-client.factory.js',
'app/common/http-error-modal/http-error-modal.js',
'app/modules/dashboards/index.js',
'app/modules/dashboards/state-dashboards.service.js',
'app/modules/dashboards/zone-dashboards.service.js',
'app/modules/data/dashboard/dashboard.controller.js',
'app/modules/data/upload/upload-form.directive.js',
'app/modules/data/inbox/inbox.controller.js',
'app/modules/data/inbox/inbox.service.js',
'app/modules/data/index.js',
'app/modules/users/users.service.js',
'app/modules/users/login-form/login-form.directive.js',
'app/modules/users/user-management-navbar-el/user-management-navbar-el.directive.js',
'app/modules/users/password-reset/password-reset.directive.js',
'app/modules/users/index.js',
'app/modules/settings/indices/index.directive.js',
'app/modules/settings/indices/indicator.directive.js',
'app/modules/settings/indices/indices.directive.js',
'app/modules/settings/indices/index.js',
'app/modules/settings/entities/entities.directive.js',
'app/modules/settings/entities/index.js',
'app/modules/settings/index.js',
'app/modules/analysis/chart.directive.js',
'app/modules/analysis/bar/bar.controller.js',
'app/modules/analysis/matrix/matrix.controller.js',
'app/modules/analysis/stock/stock.controller.js',
'app/modules/analysis/products.constant.js',
'app/modules/analysis/index.js',
'app/modules/entities/typeahead/agencies/agencies.directive.js',
'app/modules/entities/typeahead/districts/districts.directive.js',
'app/modules/entities/typeahead/regions/regions.directive.js',
'app/modules/entities/typeahead/sites/sites.directive.js',
'app/modules/entities/typeahead/zones/zones.directive.js',
'app/modules/entities/typeahead/index.js',
'app/modules/entities/admin/sites.directive.js',
'app/modules/entities/admin/site.directive.js',
'app/modules/entities/admin/zones.directive.js',
'app/modules/entities/admin/zone.directive.js',
'app/modules/entities/admin/regions.directive.js',
'app/modules/entities/admin/region.directive.js',
'app/modules/entities/admin/districts.directive.js',
'app/modules/entities/admin/district.directive.js',
'app/modules/entities/admin/index.js',
'app/modules/entities/entities.service.js',
'app/modules/entities/index.js',
//
//'app/**/*.module.js',
//'app/**/*.js',
//'app/**/*.service.js',
'app/**/*.spec.js',
//'app/**/*.html'
]),
// 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_DEBUG,
// enable / disable watching file and executing tests whenever any file changes
autoWatch: false,
// 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: true,
plugins: [
'karma-*'
]
})
}
my test is :
'use strict';
/*global module: false, inject: false */
describe('utility', function(){
var utility;
beforeEach(module('eha.van.utility'));
beforeEach(inject(function(_utility_){
utility = _utility_
}));
it('should be defined', function(){
expect(utility).toBeDefined();
});
});

Angular unit tests with Karma/Jasmine - browser not defined

Whenever I run a unit test I get the error:
browser is not defined.
My config file is below - can anyone suggest the issue
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: [
'www-dev/js/ionic.bundle.js',
'node_modules/angular-mocks/angular-mocks.js',
'www-dev/js/app.js',
'www-dev/js/templates.js',
'www-dev/css/*.css',
{pattern: 'tests/unit/unit.js', nocache: true, watched: true}
],
// 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: {
'./www-dev/js/app.js': ['coverage']
},
// test results reporter to use
// possible values: 'dots', 'progress'
// available reporters: https://npmjs.org/browse/keyword/karma-reporter
reporters: ['progress','coverage'],
coverageReporter: {
type : 'html',
dir : './tests/unit/'
},
// 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', 'Firefox', 'IE'],
// 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
})
}
To actually open a browser instance, Karma needs a browser launcher, which comes in the form of a plugin.
From Karma's browser docs:
Note: Most of the browser launchers need to be loaded as plugins.
Have you installed the correct launcher plugins?
https://github.com/karma-runner/karma-chrome-launcher
https://github.com/karma-runner/karma-firefox-launcher
https://github.com/karma-runner/karma-ie-launcher

Karma-coverage not found: But, it is installed

I used this guide http://karma-runner.github.io/0.8/config/coverage.html to setup my Karma-coverage plugin. Furthermore, it gets installed locally via the package.json file, which looks like this:
{
"name": "myApp",
"version": "0.1.0",
"devDependencies": {
"karma-jasmine": "latest",
"karma-coverage": "latest",
"karma-coffee-preprocessor": "latest",
"karma-chrome-launcher": "latest",
"coffee-script": "latest"
}
}
My Karma.conf looks like this:
// Karma configuration
// Generated on Sun Dec 07 2014 15:51:07 GMT+0100 (CET)
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: [
'javascripts/vendor/jquery_211.js',
'javascripts/vendor/angular.js',
'javascripts/vendor/angular-route.js',
'javascripts/vendor/angular-mocks.js',
'../app/assets/javascripts/app.coffee',
'javascripts/*.js',
'test/controllers/*.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: {
'../app/assets/javascripts/app.coffee' : ['coffee'],
'**/javascripts/*.js': 'coverage'
//'**/*.coffee': ['coffee']
},
// test results reporter to use
// possible values: 'dots', 'progress'
// available reporters: https://npmjs.org/browse/keyword/karma-reporter
reporters: ['progress', 'coverage'],
// 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
});
};
Now, while running karma I receive the error
WARN [reporter]: Can not load "coverage", it is not registered!
Perhaps you are missing some plugin?
INFO [karma]: Karma v0.12.28 server started at http://localhost:9876/
INFO [launcher]: Starting browser Chrome
WARN [preprocess]: Can not load "coverage", it is not registered!
Perhaps you are missing some plugin?
It does not matter, if I include karma-coverage in the plugin section of the karma.conf file, the problem stays the same (since the plugin gets loaded locally, I should not need the plugin part anyway...). I hope somebody of you guys has an idea... Thank you!
npm install -g karma-coverage to install the karma-coverage, and it will work fine, but i don't know why.
// Karma configuration
// Generated on Tue Oct 13 2015 11:14:07 GMT+0800 (CST)
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: [
'*.js'
],
// list of files to exclude
exclude: [
'karma.config.js'
],
// preprocess matching files before serving them to the browser
// available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
preprocessors: {
'*.js': 'coverage'
},
coverageReporter:{
type: 'html',
dir: './coverage'
},
// test results reporter to use
// possible values: 'dots', 'progress'
// available reporters: https://npmjs.org/browse/keyword/karma-reporter
reporters: ['progress','coverage'],
// web server port
port: 9876,
// enable / disable colors in the output (reporters and logs)
colors: true,
// level of logging
// possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
logLevel: config.LOG_INFO,
// enable / disable watching file and executing tests whenever any file changes
autoWatch: true,
// start these browsers
// available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
browsers: ['Chrome'],
// Continuous Integration mode
// if true, Karma captures browsers, runs the tests and exits
singleRun: false
})
}
The solution for this problem was that I had a couple of installed node_modules within my users home folder. After deinstalling these modules and the locally installed ones via npm, I made a clean reinstall via npm link. This solved the problem for me!
plugins: [
require('karma-jasmine'),
require('karma-coverage'),
require('karma-chrome-launcher'),
require('karma-jasmine-html-reporter'),
require('karma-coverage-istanbul-reporter'),
require('#angular-devkit/build-angular/plugins/karma')
],
After added **"karma-coverage"** into the plugins array in karma.conf.js
it works to me. Thanks

Resources