Related
I want to use visual studio code to debug karma tests in typescript file. But I don't know config because I use gulp compile .ts file to dist directory.
gulp compile js file to dist
gulp compile:
var appDev = 'src';
var appProd = __dirname + '/dist';
gulp.task('compile', function() {
return gulp.src('src/**/*.ts')
.pipe(sourcemaps.init())
.pipe(tsProject())
.js.pipe(sourcemaps.write('.'))
.pipe(gulp.dest(appProd + '/src'));
});
gulp.task('copy:index', function() {
return gulp.src(['index.html', 'systemjs.config.js'])
.pipe(gulp.dest(appProd))
});
gulp.task('copy:assets', function() {
return gulp.src(['src/**/*', '!src/**/*.ts' ], {base: './'})
.pipe(gulp.dest(appProd))
});
gulp.task('css', function() {
var lessStream = gulp.src('./less/app.less')
.pipe(less())
.pipe(concat('./less/styles.less'));
return merge(lessStream)
.pipe(concat('styles.css'))
.pipe(gulp.dest(appProd + '/styles'));
});
gulp.task('copy:node_modules', function() {
return gulp.src([
... // list file copy
], {cwd: 'node_modules/**'}) /* Glob required here. */
.pipe(gulp.dest(appProd + '/node_modules'));
});
gulp test:
gulp.task('test-compile', function() {
return gulp.src([
'./src/**/*.ts',
'./testing/**/*.ts'
], { base: '.'})
.pipe(sourcemaps.init())
.pipe(tsProject())
.js.pipe(sourcemaps.write('.'))
.pipe(gulp.dest(appProd));
});
gulp.task('test', [ 'clean', 'copy:bower_components', 'copy:node_modules', 'copy:index',
'copy:js', 'css', 'copy:html', 'test-compile', 'watch' ], function(done) {
new Server({
configFile: __dirname + '/dist/karma.conf.js'
}, done).start();
});
karma.conf.js :
module.exports = function(config) {
var appBase = 'src/'; // transpiled app JS and map files
var appAssets = __dirname + '/src/'; // component assets fetched by Angular's compiler
// Testing helpers (optional) are conventionally in a folder called `testing`
var testingBase = 'testing/'; // transpiled test JS and map files
config.set({
basePath: '.',
frameworks: ['jasmine'],
plugins: [
require('karma-jasmine'),
require('karma-chrome-launcher'),
require('karma-jasmine-html-reporter'),
require('karma-coverage'),
require('karma-remap-istanbul')
],
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.min.js',
'node_modules/reflect-metadata/Reflect.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: 'systemjs.config.js', included: false, watched: false },
'karma-test-shim.js', // optionally extend SystemJS mapping e.g., with barrels
{ pattern: 'node_modules/angular2-toaster/**/*.js', included: false, watched: false },
{ pattern: 'node_modules/ng2-cookies/**/*.js', included: false, watched: false },
{ pattern: 'node_modules/lodash/**/*.js', included: false, watched: false },
{ pattern: 'node_modules/dragula/**/*.js', included: false, watched: false },
{ pattern: 'node_modules/ng2-dragula/**/*.js', included: false, watched: false },
{ pattern: 'node_modules/ng2-select/**/*.js', included: false, watched: false },
{ pattern: 'node_modules/ng2-bootstrap/**/*.js', included: false, watched: false },
{ pattern: 'node_modules/ng2-dnd/**/*.js', included: false, watched: false },
{ pattern: 'node_modules/ng2-uploader/**/*.js', included: false, watched: false },
{ pattern: 'node_modules/moment/**/*.js', included: false, watched: false },
{ pattern: 'bower_components/jquery/dist/jquery.min.js', watched: false },
{ pattern: 'bower_components/bootstrap/dist/js/bootstrap.min.js', watched: false },
{ pattern: 'node_modules/**/*.js.map', included: false, watched: false },
// 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: 'styles/*.css', included: false, watched: true },
// Paths for debugging with source maps in dev tools
{ pattern: appBase + '**/*.js.map', included: false, watched: false },
{ pattern: testingBase + '**/*.js.map', included: false, watched: false }
],
// Proxied base paths for loading assets
proxies: {
// required for component assets fetched by Angular's compiler
'/src/': appAssets
},
exclude: [],
preprocessors: {
'src/**/*.js': ['coverage']
},
reporters: ['progress', 'coverage', 'karma-remap-istanbul'],
remapIstanbulReporter: {
reports: {
html: 'coverage'
}
},
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ['Chrome'],
singleRun: false
})
}
Help me config karma to debug with typescript file use VSCode
I am working on a project using angular 2 and a 3rd party library for making charts (AmCharts). I figured out how to use it along angular 2, but I'm getting a error when I try to make a unit test for the chart component:
Error: Error in ./ChartsComponent class ChartsComponent - inline template:1:2 caused by: AmCharts is not defined
ReferenceError: AmCharts is not defined
This project has been created using angular-cli and we've recently upgraded angular to version 2.2.1.
Here is angular-cli.json and karma.conf.js:
angular-cli.json
{
"project": {
"version": "1.0.0-beta.21",
"name": "cli-crud-webpack"
},
"apps": [
{
"root": "src",
"outDir": "dist",
"assets": [
"assets",
"favicon.ico"
],
"index": "index.html",
"main": "main.ts",
"test": "test.ts",
"tsconfig": "tsconfig.json",
"prefix": "gov",
"mobile": false,
"styles": [
"styles.scss",
"../public/assets/css/agate.css",
"../public/assets/css/bootstrap.min.css"
],
"scripts": [
"../public/assets/js/highlight.pack.js",
"../node_modules/amcharts3/amcharts/amcharts.js",
"../node_modules/amcharts3/amcharts/xy.js",
"../node_modules/amcharts3/amcharts/gauge.js",
"../node_modules/amcharts3/amcharts/serial.js",
"../node_modules/amcharts3/amcharts/pie.js",
"../node_modules/amcharts3/amcharts/themes/light.js",
"../node_modules/amcharts3/amcharts/themes/dark.js",
"../node_modules/amcharts3/amcharts/themes/black.js",
"../node_modules/amcharts3/amcharts/plugins/responsive/responsive.min.js"
],
"environments": {
"source": "environments/environment.ts",
"dev": "environments/environment.ts",
"prod": "environments/environment.prod.ts"
}
}
],
"addons": [],
"packages": [],
"e2e": {
"protractor": {
"config": "./protractor.conf.js"
}
},
"test": {
"karma": {
"config": "./karma.conf.js"
}
},
"defaults": {
"styleExt": "scss",
"prefixInterfaces": false,
"inline": {
"style": false,
"template": false
},
"spec": {
"class": false,
"component": true,
"directive": true,
"module": false,
"pipe": true,
"service": true
}
}
}
karma.conf.js
module.exports = function (config) {
config.set({
basePath: '',
frameworks: ['jasmine', 'angular-cli'],
plugins: [
require('karma-jasmine'),
require('karma-chrome-launcher'),
require('karma-remap-istanbul'),
require('angular-cli/plugins/karma')
],
files: [
{ pattern: './src/test.ts', watched: false }
],
preprocessors: {
'./src/test.ts': ['angular-cli']
},
mime: {
'text/x-typescript': ['ts','tsx']
},
remapIstanbulReporter: {
reports: {
html: 'coverage',
lcovonly: './coverage/coverage.lcov'
}
},
angularCli: {
config: './angular-cli.json',
environment: 'dev'
},
reporters: config.angularCli && config.angularCli.codeCoverage
? ['progress', 'karma-remap-istanbul']
: ['progress'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ['Chrome'],
singleRun: false
});
};
I just found out I have to declare amcharts in karma configuration file, like this:
module.exports = function (config) {
config.set({
basePath: '',
frameworks: ['jasmine', 'angular-cli'],
plugins: [
require('karma-jasmine'),
require('karma-chrome-launcher'),
require('karma-remap-istanbul'),
require('angular-cli/plugins/karma')
],
files: [
{ pattern: './src/test.ts', watched: false },
"./public/assets/js/highlight.pack.js",
"./node_modules/amcharts3/amcharts/amcharts.js",
"./node_modules/amcharts3/amcharts/xy.js",
"./node_modules/amcharts3/amcharts/gauge.js",
"./node_modules/amcharts3/amcharts/serial.js",
"./node_modules/amcharts3/amcharts/pie.js",
"./node_modules/amcharts3/amcharts/themes/light.js",
"./node_modules/amcharts3/amcharts/themes/dark.js",
"./node_modules/amcharts3/amcharts/themes/black.js",
"./node_modules/amcharts3/amcharts/plugins/responsive/responsive.min.js"
],
preprocessors: {
'./src/test.ts': ['angular-cli']
},
mime: {
'text/x-typescript': ['ts','tsx']
},
remapIstanbulReporter: {
reports: {
html: 'coverage',
lcovonly: './coverage/coverage.lcov'
}
},
angularCli: {
config: './angular-cli.json',
environment: 'dev'
},
reporters: config.angularCli && config.angularCli.codeCoverage
? ['progress', 'karma-remap-istanbul']
: ['progress'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ['Chrome'],
singleRun: false
});
};
How do I set up karma-coverage with angular2 + webpack?
I followed the quickstart webpack guide from angular. But the coverage tool is blank and does not display my tests. Thanks!
my folder structure is
project
|--src (project files)
|--tests (all my testfiles)
my webpack.test.js looks like this
var helpers = require('./helpers');
module.exports = {
devtool: 'inline-source-map',
resolve: {
extensions: ['', '.ts', '.js']
},
module: {
loaders: [
{
test: /\.ts$/,
loaders: ['ts']
},
{
test: /\.html$/,
loader: 'null'
},
{
test: /\.(png|jpe?g|gif|svg|woff|woff2|ttf|eot|ico)$/,
loader: 'null'
},
{
test: /\.css$/,
exclude: helpers.root('src', 'app'),
loader: 'null'
},
{
test: /\.css$/,
include: helpers.root('src', 'app'),
loader: 'null'
}
]
}
}
my Karma.conf.js
var webpackConfig = require('./webpack.test');
module.exports = function (config) {
var _config = {
basePath: '',
frameworks: ['jasmine', 'sinon'],
files: [
{pattern: './config/karma-test-shim.js', watched: false}
],
preprocessors: {
'./config/karma-test-shim.js': ['webpack', 'sourcemap']
},
plugins:[
require('karma-jasmine'),
require('karma-coverage'),
require('karma-webpack'),
require('karma-phantomjs-launcher'),
require('karma-sourcemap-loader'),
require('karma-mocha-reporter'),
require('karma-sinon')
],
coverageReporter: {
type : 'html',
dir : 'coverage/'
},
webpack: webpackConfig,
webpackMiddleware: {
stats: 'errors-only'
},
webpackServer: {
noInfo: true
},
reporters: ['mocha','coverage'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ['PhantomJS'],
singleRun: false
};
config.set(_config);
};
and the karma-test-shim.js
Error.stackTraceLimit = Infinity;
require('core-js/es6');
require('reflect-metadata');
require('zone.js/dist/zone');
require('zone.js/dist/long-stack-trace-zone');
require('zone.js/dist/proxy');
require('zone.js/dist/sync-test');
require('zone.js/dist/jasmine-patch');
require('zone.js/dist/async-test');
require('zone.js/dist/fake-async-test');
var testContext = require.context('../tests', true, /\.spec\.ts/);
testContext.keys().forEach(testContext);
var testing = require('#angular/core/testing');
var browser = require('#angular/platform-browser-dynamic/testing');
testing.TestBed.initTestEnvironment(browser.BrowserDynamicTestingModule, browser.platformBrowserDynamicTesting());
Yuu need to import below code coverage plugin into plugins
require('karma-coverage-istanbul-reporter'),
Also, use below code to add istanbul reporter property as below
coverageIstanbulReporter: {
reports: ['html', 'lcovonly'],
fixWebpackSourcePaths: true,
// enforce percentage thresholds
// anything under these percentages will cause karma to fail with an exit code of 1 if not running in watch mode
thresholds: {
emitWarning: false, // set to `true` to not fail the test command when thresholds are not met
global: { // thresholds for all files
statements: 80,
lines: 80,
branches: 80,
functions: 80
},
each: { // thresholds per file
statements: 80,
lines: 80,
branches: 80,
functions: 80,
overrides: {}
}
}
},
The complete config for karma.config.js should be below:
// Karma configuration file, see link for more information
// https://karma-runner.github.io/0.13/config/configuration-file.html
module.exports = function(config) {
config.set({
basePath: '',
frameworks: ['jasmine', '#angular/cli'],
plugins: [
require('karma-jasmine'),
require('karma-chrome-launcher'),
require('karma-jasmine-html-reporter'),
require('karma-coverage-istanbul-reporter'),
require('#angular/cli/plugins/karma'),
require('karma-htmlfile-reporter'),
],
client: {
clearContext: false // leave Jasmine Spec Runner output visible in browser
},
coverageIstanbulReporter: {
reports: ['html', 'lcovonly'],
fixWebpackSourcePaths: true,
// enforce percentage thresholds
// anything under these percentages will cause karma to fail with an exit code of 1 if not running in watch mode
thresholds: {
emitWarning: false, // set to `true` to not fail the test command when thresholds are not met
global: { // thresholds for all files
statements: 80,
lines: 80,
branches: 80,
functions: 80
},
each: { // thresholds per file
statements: 80,
lines: 80,
branches: 80,
functions: 80,
overrides: {}
}
}
},
angularCli: {
environment: 'dev'
},
// reporters: config.angularCli && config.angularCli.codeCoverage ? ['spec', 'karma-remap-istanbul'] : ['spec'],
// reporters: ['mocha'],
reporters: ['progress', 'html', 'kjhtml'],
htmlReporter: {
outputFile: 'testreports/report.html',
// Optional
pageTitle: 'Rest Reports',
subPageTitle: 'Suite-wise report ',
groupSuites: true,
useCompactStyle: true,
useLegacyStyle: false
},
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ['Chrome'],
singleRun: false
});
};
How to configure karma to stop loading images while testing? i was trying to use solution from here in my karma.config.js :
var webpack = require('webpack');
module.exports = function (config) {
config.set({
browsers: [ 'Chrome' ],
singleRun: true,
frameworks: [ 'mocha' ],
files: [
'tests.webpack.js',
{pattern: './assets/img/signup.png', watched: false, included: false, served: true},
],
proxies: {
'/assets/img/signup.png': '/assets/img/signup.png'
},
preprocessors: {
'tests.webpack.js': [ 'webpack', 'sourcemap' ]
},
reporters: ['mocha'],
mochaReporter: {},
webpack: {
devtool: 'inline-source-map',
module: {
loaders: [
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel-loader',
query: {
cacheDirectory: true,
plugins: ['transform-decorators-legacy' ],
presets: ['airbnb', 'es2015', 'stage-1', 'react']
}
}
]
},
externals: {
'cheerio': 'window',
'react/addons': true,
'react/lib/ExecutionEnvironment': true,
'react/lib/ReactContext': true
}
},
webpackServer: {
noInfo: true //please don't spam the console when running in karma!
}
});
};
but this doesn't work for me. I still get error:
[web-server]: 404: /front-end2/assets/img/signup.png
Maybe there are any other solution to prevent loading images ? the biggest problem is not warning message but errors which ocures when karma try to get image from my local server
The proxies configuration does not look right. Try something like this:
...
proxies: {
'/front-end2/assets/img/': '/base/assets/img/'
},
...
A brief explanation:
/front-end2/assets/img/ relates to the requests that are being made;
/assets/img/ relates the the pattern in the files configuration; and
/base/ is the path from which Karma serves the files.
I've been trying to run karma coverage for a couple of days now only to find an empty blank page as below.
Here's my configuration:
var path = require('path');
var webpackConfig = require('./webpack.common');
module.exports = function (config) {
var _config = {
basePath: '',
frameworks: ['jasmine'],
files: [
{ pattern: './karma-shim.js', watched: false }
],
exclude: [],
preprocessors: {
'./karma-shim.js': ['webpack', 'sourcemap', 'coverage']
},
client: {
captureConsole: false
},
webpack: webpackConfig,
webpackMiddleware: {
stats: 'errors-only'
},
coverageReporter: {
dir: 'coverage/',
reporters: [{
type: 'json',
dir: 'coverage',
subdir: 'json',
file: 'coverage-final.json'
}]
},
remapIstanbulReporter: {
src: 'coverage/json/coverage-final.json',
reports: {
lcovonly: 'coverage/json/lcov.info',
html: 'coverage/html',
'text': null
},
timeoutNotCreated: 1000, // default value
timeoutNoMoreFiles: 1000 // default value
},
webpackServer: {
noInfo: true // please don't spam the console when running in karma!
},
reporters: ["mocha", "coverage", "karma-remap-istanbul"],
port: 9876,
colors: true,
logLevel: config.LOG_ERROR,
autoWatch: false,
browsers: ['PhantomJS'], // you can also use Chrome
singleRun: true
};
config.set(_config);
};
And here's my karma-shim.js file
Error.stackTraceLimit = Infinity;
require('es6-shim');
require('reflect-metadata');
require('ts-helpers');
require('zone.js/dist/zone');
require('zone.js/dist/long-stack-trace-zone');
require('zone.js/dist/jasmine-patch');
require('zone.js/dist/async-test');
require('zone.js/dist/fake-async-test');
var appContext = require.context('./app', true, /\.spec\.ts/);
appContext.keys().forEach(appContext);
var testing = require('#angular/core/testing');
var browser = require('#angular/platform-browser-dynamic/testing');
testing.setBaseTestProviders(browser.TEST_BROWSER_DYNAMIC_PLATFORM_PROVIDERS, browser.TEST_BROWSER_DYNAMIC_APPLICATION_PROVIDERS);
Folder Structure is as follows:
Any idea what am i missing here? Help much appreciated.
Thanks
Your karma config is clearly missing a reference to the source.
Please modify config as follows:
module.exports = function (config) {
var _config = {
[...]
preprocessors: {
// Remove coverage as preprocessor for your tests -
// Istambul (runs coverage behind the scene for karma) will
// instrumentate this
'./karma-shim.js': ['webpack', 'sourcemap'],
// Add path to your source (.js or .ts - depands on your project)
'./index.ts': [ 'coverage' ]
},
[...]
},
[...]
}
Explanation: coverage tests your code against your unit tests - you need to supply entry point for your code to get Karma analyse coverage.
Extras - adding karma-coverage plugin:
module.exports = function (config) {
var _config = {
[...]
plugins: [
require( 'karma-coverage' )
],
[...]
},
[...]
}
Extras - karma & typescript files:
module.exports = function (config) {
var _config = {
[...]
plugins: [
require( '#angular/cli/plugins/karma' )
],
[...]
},
[...]
preprocessors: {
'./src/test.ts': [ '#angular/cli' ],
'./index.ts': [ 'coverage' ]
},
[...]
mime: {
'text/x-typescript': [ 'ts', 'tsx' ]
},
[...]
}
I've got the same problem, and I've tried everything I could find on the Internet, but nothing worked. So I solved it in the following HARD but VERY SIMPLE way:
Create a new folder, or delete all the content of the existing folder of your project (YOU'D NEED TO ADD, COMMIT, AND PUSH EVERYTHING IF YOU DELETE THE CONTENT), and then clone the same project all over again.
As usual, run command "npm install".
Then copy the following karma.conf.js file content to replace your own karma.conf.js file content:
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'),
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: false,
});
};
Most likely, it's the 'coverage' part that is wrong in
dir: require('path').join(__dirname, 'coverage'),
In my case, the original setup was
dir: require('path').join(__dirname, './../coverage/360-app'),
which gave me a hard time. But since you set it up wrong in the beginning, it'd be hard to get it right even if you change it.
After I did the re-clone, I started to have everything I want:
Good luck to everyone.