karma-coverage files not created while singleRun = true - angularjs

I am using Karma to run my unit tests and am now trying to incorporate karma-coverage into my process.
I am using PhantomJS to run the tests with singleRun: true. Whenever I do this, my code coverage reporter does not seem to be running. If I set singleRun: false, the folder and files are created.
Why is the karma coverage tool not running?
Here is my config file:
module.exports = function (config) {
config.set({
basePath: '',
frameworks: ['mocha', 'requirejs', 'sinon-chai'],
files: [
{ pattern: 'bower_components/angular/angular.js', included: false },
{ pattern: 'bower_components/jquery/dist/jquery.js', included: false },
{ pattern: 'bower_components/angular-mocks/angular-mocks.js', included: false },
{ pattern: '**/*.js', included: false },
{ pattern: 'KarmaTests/test-main.js', included: true },
{ pattern: 'KarmaTests/**/*Test*.js', included: false }
],
preprocessors: {
'KarmaTests/*/*.js': ['coverage']
},
reporters: ['progress', 'coverage'],
coverageReporter: {
type: 'html',
dir: '_testCoverage/',
file: 'cover.html'
},
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ['PhantomJS'],
//files are created when false, are not when true
singleRun: false
});
};

Preprocessor is intended to map the source files, not the test files. Do the following:
Change the preprocessor pattern to:
preprocessors: {
'/**/*.js': ['coverage']
},
And add the JS files to the test mapping:
{ pattern: '**/*.js', included: true }
Rerun karma and view the results

Related

Unit Testing Hybrid Angular Js and Angular 8 Application

I'm working on a angular js and angular 8 hybrid application. The new components created in angular are downgraded to be used in angular js. Code snippet of module is shown below:
#NgModule({
// Declaration and Imports
providers:[
ServiceName,
// Other Services
],
entryComponents: [
ComponentName,
// Other components to be used in angular js
]
})
export class FeatureModule{
}
declare var angular: angular.IAngularStatic
angular.module('app')
.directive('cmpName', downgradeComponent({component: ComponentName }) as angular.IDirectiveFactory)
.factory('serviceName', downgradeInjectable(ServiceName));
In app.module.ts file, there is following code.
// Usual Stuff
export class AppModule {
constructor(
private upgrade: UpgradeModule,
) {
}
ngDoBootstrap() {
this.upgrade.bootstrap(document.body, ['app'], { strictDi: true });
}
}
Nothing has been updated in component spec file generated by angular cli.
In tsconfig.spec.json,
{
"extends": "../tsconfig.json",
"compilerOptions": {
"baseUrl": "./",
"outDir": "../out-tsc/spec",
"types": ["jasmine", "node", "angular"]
},
"files": ["test.ts", "polyfills.ts"],
"include": ["**/*.spec.ts", "**/*.d.ts"]
}
karma.conf.js looks like below.
module.exports = function (config) {
config.set({
basePath: '',
frameworks: ['jasmine', '#angular-devkit/build-angular'],
plugins: [
require('karma-jasmine'),
require('karma-chrome-launcher'),
require('karma-jasmine-html-reporter'),
require('karma-coverage-istanbul-reporter'),
require('#angular-devkit/build-angular/plugins/karma')
],
client: {
clearContext: false // leave Jasmine Spec Runner output visible in browser
},
coverageIstanbulReporter: {
dir: require('path').join(__dirname, '../coverage/ProjectFolder'),
reports: ['html', 'lcovonly', 'text-summary'],
fixWebpackSourcePaths: true
},
reporters: ['progress', 'kjhtml'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ['Chrome'],
singleRun: false,
restartOnFileChange: true
});
};
Now, if I run npm run test or ng test command to run test suite, I'm getting following error.
An error was thrown in afterAll Uncaught ReferenceError: angular is not defined ReferenceError: angular is not defined at Module../..path-to-module-file/feature.module.ts.
How can I resolve this issue? Do I have to mock angular variable declared in the module file. Any help is appreciated?
I don't know too much of the nitty gritty details, but I run a hybrid application with Webpack and Karma. I downgrade all my components so they can be used in AngularJS, just like you.
The difference is that I have a file called vendor.ts that contains AngularJS. I bet you do too, since you only talk about the tests failing, not the product being broken. I have an entry in my Karma config file:
files: [
{ pattern: "node_modules/babel-polyfill/dist/polyfill.js", watched: false },
{ pattern: "node_modules/intl/locale-data/jsonp/en-GB.js", watched: false },
{ pattern: "node_modules/intl/locale-data/jsonp/fr-FR.js", watched: false },
{ pattern: "static/polyfills.ts", watched: false },
{ pattern: "static/vendor.ts", watched: false },
{ pattern: "node_modules/zone.js/dist/long-stack-trace-zone.js", watched: false },
{ pattern: "node_modules/zone.js/dist/proxy.js", watched: false },
{ pattern: "node_modules/zone.js/dist/sync-test.js", watched: false },
{ pattern: "node_modules/zone.js/dist/jasmine-patch.js", watched: false },
{ pattern: "node_modules/zone.js/dist/async-test.js", watched: false },
{ pattern: "node_modules/zone.js/dist/fake-async-test.js", watched: false },
{ pattern: "node_modules/angular-mocks/angular-mocks.js", watched: false },
{ pattern: "static/main.ts", watched: false },
{ pattern: "static/main.test.ts", watched: false },
],
This tells Karma which files to watch and serve in the browser. I think that means that after Webpack compiled these files, Karma-Webpack can find the compiled files and serve them.

Getting this error "Error: beforeEach expects a function argument; received [object Object]" while testing angularjs using karma and jasmine

I am getting this error "Error: beforeEach expects a function argument; received [object Object]" while testing angularjs using karma and jasmine. I have tried in so many ways but couldn't get the solution. I have given below my spec code and karma conf js. For your information I do use requirejs in my application due to some dependencies
//Service Spec code :
define([], function () {
'use strict';
describe('search Service spec', function () {
var searchService;
beforeEach(angular.module('flightRouteApp', []));
describe('service methods', function () {
it('should calculate the length of the element', inject(function (searchService) {
expect(searchService).toBeDefined();
}));
});
});
});
// Karma configuration
// Generated on Sun Mar 05 2017 09:17:46 GMT+0100 (W. Europe Standard Time)
/* global module */
"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','requirejs'],
// list of files / patterns to load in the browser
files: [
{pattern:'node_modules/angular/angular.js',watched: true, included: true, served: true},
{pattern:'node_modules/angular-mocks/angular-mocks.js',watched: true, included: true, served: true},
{pattern:'app/js/flightRoute.js',watched: true, included: true, served: true},
{pattern:'app/js/services/*.js',watched: true, included: true, served: true},
{pattern:'app/js/**/*.js',watched: true, included: true, served: true},
{pattern:'tests/test-main.js',watched: true, included: true, served: true},
{pattern: 'tests/**/*.Spec.js',watched: true, included: true, served: true}
],
// list of files to exclude
exclude: [ ],
// test results reporter to use
// possible values: 'dots', 'progress'
// available reporters: https://npmjs.org/browse/keyword/karma-reporter
/*reporters: ['progress','coverage'],*/
reporters: config.angularCli && config.angularCli.codeCoverage
? ['progress', 'coverage-istanbul']
: ['progress', 'kjhtml'],
preprocessors: {
'app/js/**/*.js': 'coverage'
},
// web server port
port: 9876,
coverageReporter: {includeAllSources: true, reporters:[{type: 'html', dir:'coverage/'}]},
// enable / disable colors in the output (reporters and logs)
colors: true,
//vel 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
// 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
})
}
Just change your beforeEach do this:
beforeEach(module('flightRouteApp'));

karma unable to find test files

I am using karma, browserify and babelify to run unit tests for angular 2.
Whenever I run it it fails with a 404 error like this
25 05 2017 11:35:22.974:WARN [web-server]: 404: /C://Users//me//git//proj-ng//modules//pack\\src//test.service.spec.js
Firefox 53.0.0 (Windows 7 0.0.0) ERROR
(SystemJS) XHR error (404 Not Found) loading http://localhost:9876/C:\\Users\\me\\git\\proj-ng\\modules\\pack\\src\\test.s
ervice.spec.js
wrapFn#C:/Users/me/git/proj-ng/modules/pack/node_modules/zone.js/dist/zone.js:1055:30
ZoneDelegate.prototype.invokeTask#C:/Users/me/git/proj-ng/modules/pack/node_modules/zone.js/dist/zone.js:424:17
Zone.prototype.runTask#C:/Users/me/git/proj-ng/modules/pack/node_modules/zone.js/dist/zone.js:191:28
ZoneTask/this.invoke#C:/Users/me/git/proj-ng/modules/pack/node_modules/zone.js/dist/zone.js:486:28
Error loading http://localhost:9876/C:\\Users\\me\\git\\proj-ng\\modules\\pack\\src\\test.service.spec.js as "C:\\Users\\me\\git\\proj-ng\\modules\\pack\\src\\test.service.spec.js" from http://localhost:9876/src/test.service.spec.js
I have checked that the test files are located at the location it is complaining about. I have tried many variations and am out of ideas by now on what can be wrong.
Below is my karma.conf.js.
(function () {
"use strict";
module.exports = function (config) {
config.set({
basePath: "",
frameworks: ["browserify","jasmine"],
browsers: ["Firefox"],
reporters: ["mocha", "coverage"],
// Source files that you wanna generate coverage for.
preprocessors: {"src/**/!(*spec).js": ["coverage", "sourcemap"], "src/**/*.js": ["browserify"]},
// "src/**/!(*spec).js": ["browserify"]},
browserify: {
debug: true,
transform: [ "babelify" ]
},
coverageReporter: {
dir: "code-coverage/",
reporters: [
{type: "text-summary"},
{type: "json"},
{type: "html"}
]
},
files: [
"node_modules/es6-shim/es6-shim.js",
"node_modules/reflect-metadata/Reflect.js",
"node_modules/systemjs/dist/system-polyfills.js",
"node_modules/systemjs/dist/system.src.js",
"node_modules/zone.js/dist/zone.js",
"node_modules/zone.js/dist/long-stack-trace-zone.js",
"node_modules/zone.js/dist/async-test.js",
"node_modules/zone.js/dist/fake-async-test.js",
"node_modules/zone.js/dist/sync-test.js",
"node_modules/zone.js/dist/proxy.js",
"node_modules/zone.js/dist/jasmine-patch.js",
{pattern: "node_modules/rxjs/**/*.js", included: false, watched: false},
{pattern: "node_modules/rxjs/**/*.js.map", included: false, watched: false},
{pattern: "node_modules/angular-2-local-storage/**/*.js", included: false, watched: false},
{pattern: "karma-test-shim.js", included: true, watched: true},
{pattern: "node_modules/#angular/**/*.js", included: false, watched: true},
{pattern: "node_modules/#angular/**/*.js.map", included: false, watched: true},
{pattern: "src/**/*.js", included: false, watched: true},
// paths to support debugging with source maps in dev tools
{pattern: "src/**/*.ts", included: false, watched: false},
{pattern: "src/**/*.js.map", included: false, watched: false}
],
proxies: {
// required for component assets fetched by Angular"s compiler
"/src/": "/base/src/"
},
port: 9876,
colors: true,
logLevel: config.LOG_DEBUG,
autoWatch: false,
singleRun: true
});
};
}());
my gulp test task is simply
const Server = require("karma").Server;
gulp.task("test", () => {
new Server({
configFile: __dirname + '/karma.conf.js'
}).start();
});

Angular 4 Karma Unit Testing, not detecting the tests

I am trying to introduce unit testing to my Angular 4 project. I am using Karma for it. I have done the configuration. It shows a connected screen. But it shows not tests! I have one test under src/app/ directory.
This error appears in console.
{
"originalErr": {
"__zone_symbol__currentTask": {
"type": "microTask",
"state": "notScheduled",
"source": "Promise.then",
"zone": "<root>",
"cancelFn": null,
"runCount": 0
}
},
"__zone_symbol__currentTask": {
"type": "microTask",
"state": "notScheduled",
"source": "Promise.then",
"zone": "<root>",
"cancelFn": null,
"runCount": 0
}
}
1st.spec.ts
describe('1st tests', () => {
it('true is true', () => expect(true).toBe(true));
});
karma.config.js
module.exports = function(config) {
var appBase = 'src/'; // transpiled app JS and map files
var appAssets = '/base/app/'; // component assets fetched by Angular's compiler
// Testing helpers (optional) are conventionally in a folder called `testing`
var testingBase = 'src/testing/'; // transpiled test JS and map files
var testingSrcBase = 'src/testing/'; // test source TS files
config.set({
basePath: '',
frameworks: ['jasmine'],
plugins: [
require('karma-jasmine'),
require('karma-chrome-launcher'),
require('karma-jasmine-html-reporter')
],
client: {
builtPaths: [appBase, testingBase], // add more spec base paths as needed
clearContext: false // leave Jasmine Spec Runner output visible in browser
},
customLaunchers: {
// From the CLI. Not used here but interesting
// chrome setup for travis CI using chromium
Chrome_travis_ci: {
base: 'Chrome',
flags: ['--no-sandbox']
}
},
files: [
// System.js for module loading
'node_modules/systemjs/dist/system.src.js',
// Polyfills
'node_modules/core-js/client/shim.js',
// zone.js
'node_modules/zone.js/dist/zone.js',
'node_modules/zone.js/dist/long-stack-trace-zone.js',
'node_modules/zone.js/dist/proxy.js',
'node_modules/zone.js/dist/sync-test.js',
'node_modules/zone.js/dist/jasmine-patch.js',
'node_modules/zone.js/dist/async-test.js',
'node_modules/zone.js/dist/fake-async-test.js',
// RxJs
{ pattern: 'node_modules/rxjs/**/*.js', included: false, watched: false },
{ pattern: 'node_modules/rxjs/**/*.js.map', included: false, watched: false },
// Paths loaded via module imports:
// Angular itself
{ pattern: 'node_modules/#angular/**/*.js', included: false, watched: false },
{ pattern: 'node_modules/#angular/**/*.js.map', included: false, watched: false },
{ pattern: appBase + '/systemjs.config.js', included: false, watched: false },
{ pattern: appBase + '/systemjs.config.extras.js', included: false, watched: false },
'karma-test-shim.js', // optionally extend SystemJS mapping e.g., with barrels
// transpiled application & spec code paths loaded via module imports
{ pattern: appBase + '**/*.js', included: false, watched: true },
{ pattern: testingBase + '**/*.js', included: false, watched: true },
// Asset (HTML & CSS) paths loaded via Angular's component compiler
// (these paths need to be rewritten, see proxies section)
{ pattern: appBase + '**/*.html', included: false, watched: true },
{ pattern: appBase + '**/*.css', included: false, watched: true },
// Paths for debugging with source maps in dev tools
{ pattern: appBase + '**/*.ts', included: false, watched: false },
{ pattern: appBase + '**/*.js.map', included: false, watched: false },
{ pattern: testingSrcBase + '**/*.ts', included: false, watched: false },
{ pattern: testingBase + '**/*.js.map', included: false, watched: false}
],
// Proxied base paths for loading assets
proxies: {
// required for modules fetched by SystemJS
'/base/src/node_modules/': '/base/node_modules/'
},
exclude: [],
preprocessors: {},
reporters: ['progress', 'kjhtml'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ['Chrome'],
singleRun: false
})
}
Karma Connection Screen:
Any lead to help, will be helpful.

AngularJS, RequireJS, Karma - Test File not loading

I'm currently attempting to run tests using Karma, however I can't seem to load the Test file...
this is my file structure:
app
controllers
..
directives
..
..
test
customersControllerTest.js
karma.conf.js
test-main.js
..
this is my current karma.conf.js 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', 'requirejs'],
// list of files / patterns to load in the browser
files: [
{pattern: './scripts/jquery.js', included: true},
{pattern: './scripts/angular.js', included: true},
{pattern: './scripts/angular-mocks.js', included: true},
'test-main.js',
{pattern: './test/*.js', included: false},
{pattern: './app/**/*.js', included: false},
],
// list of files to exclude
exclude: [
'**/*.css',
'**/bootstrap.js',
'**/routes.js',
'**/conf.js',
'**/app.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', 'Chrome', 'Firefox'],
plugins: [
'karma-*',
],
// Continuous Integration mode
// if true, Karma captures browsers, runs the tests and exits
singleRun: false
});
};
and my test-main.js file:
var testPaths = {
'customersControllersTest': '../test/customersControllersTest'
}, tests = Object.keys(window.__karma__.files).filter(function(file) {
return (/(spec|Test)\.js$/i.test(file));
}).map(function(test) {
var returnVal = false;
Object.keys(testPaths).map(function(path){
if(testPaths[path] === test.replace('/base', '..').replace('.js', '')) {
returnVal = path;
}
});
return returnVal;
});
require.config({
// Karma serves files under /base, which is the basePath from your config file
baseUrl: '/base/app',
paths: {
'jquery': '../scripts/jquery',
'angular': '../scripts/angular',
'angularMocks': '../scripts/angular-mocks',
// Modules
'servicesModule': './services/module',
'directivesModule': './directives/module',
'controllersModule': './controllers/module',
// Controllers
'testController': './controllers/testController',
'ordersController': './controllers/ordersController',
'allordersController': './controllers/allordersController',
'customersController': './controllers/customersController',
// Directives
'barChart': './directives/barsChartDirective',
'blueBarChart': './directives/blueBarsChartDirective',
// Services
'testService': './services/testService',
'routeResolver': './services/routeResolver',
'customersFactory': './services/customersFactory',
// Tests
'customersControllersTest': '../test/customersControllersTest'
},
// angular does not support AMD out of the box, put it in a shim
shim: {
'angular': {
deps: ['jquery'],
exports: 'angular'
},
'angularRoute': ['angular'],
'angularAnimate': ['angular'],
'angularMocks': ['angular']
},
// dynamically load all test files
deps: tests,
// we have to kickoff jasmine, as it is asynchronous
callback: window.__karma__.start()
});
and my customersControllersTest.js:
define('customersControllersTest', [], function() {
describe('test', function() {
console.log(this);
it('test1', function() {
expect('this').toEqual('this');
});
console.log(this);
});
});
By checking in Chrome's devtools, it gives an Error:
but when I open it:
This however might be completely unrelated, since I keep getting the following:
which, asides for saying it found no test, is yelling Error...
Any ideas on how I can tackle this?
One problem is the line:
callback: window.__karma__.start()
This calls start right away instead of passing it as callback. This line should have been
callback: window.__karma__.start
See karma-requirejs README.

Resources