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
Related
my application is running good but unit test doesn't work.
below error throws when i try to npm test
**
help me to resolve my issue
and whats the correct procedure to follow angular2 unit test,
thanks in advance..
package.json
{
"name": "angular-quickstart",
"version": "1.0.0",
"description": "QuickStart package.json from the documentation, supplemented with testing support",
"scripts": {
"start": "tsc && concurrently \"tsc -w\" \"lite-server\" ",
"docker-build": "docker build -t ng2-quickstart .",
"docker": "npm run docker-build && docker run -it --rm -p 3000:3000 -p 3001:3001 ng2-quickstart",
"pree2e": "npm run webdriver:update",
"e2e": "tsc && concurrently \"http-server -s\" \"protractor protractor.config.js\" --kill-others --success first",
"lint": "tslint ./app/**/*.ts -t verbose",
"lite": "lite-server",
"postinstall": "typings install",
"test": "tsc && concurrently \"tsc -w\" \"karma start karma.conf.js\"",
"test-once": "tsc && karma start karma.conf.js --single-run",
"tsc": "tsc",
"tsc:w": "tsc -w",
"typings": "typings",
"webdriver:update": "webdriver-manager update"
},
"keywords": [],
"author": "KOC",
"license": "ISC",
"dependencies": {
"#angular/common": "2.0.0",
"#angular/compiler": "2.0.0",
"#angular/core": "2.0.0",
"#angular/forms": "2.0.0",
"#angular/http": "2.0.0",
"#angular/platform-browser": "2.0.0",
"#angular/platform-browser-dynamic": "2.0.0",
"#angular/router": "3.0.0",
"#angular/upgrade": "2.0.0",
"angular-2-local-storage": "0.0.19",
"angular-in-memory-web-api": "~0.1.0",
"angular2-google-maps": "^0.15.0",
"angular2-highcharts": "^0.3.4",
"angular2-logger": "^0.5.0",
"bootstrap": "^3.3.6",
"core-js": "^2.4.1",
"ng2-modal": "0.0.21",
"ng2-pagination": "^0.5.1",
"reflect-metadata": "^0.1.3",
"rxjs": "5.0.0-beta.12",
"systemjs": "0.19.38",
"zone.js": "^0.6.23"
},
"devDependencies": {
"concurrently": "^2.2.0",
"lite-server": "^2.2.2",
"typescript": "^2.0.3",
"typings": "^1.4.0",
"canonical-path": "0.0.2",
"http-server": "^0.9.0",
"tslint": "^3.15.1",
"lodash": "^4.16.1",
"jasmine-core": "~2.5.2",
"karma": "^1.3.0",
"karma-chrome-launcher": "^2.0.0",
"karma-cli": "^1.0.1",
"karma-htmlfile-reporter": "^0.3.4",
"karma-jasmine": "^1.0.2",
"karma-jasmine-html-reporter": "^0.2.2",
"protractor": "^3.3.0",
"rimraf": "^2.5.2",
"#types/core-js": "^0.9.34"
},
"repository": {},
"main": "karma-test-shim.js"
}
**
karma.conf.js
**
// #docregion
module.exports = function(config) {
var appBase = 'app/'; // transpiled app JS and map files
var appSrcBase = 'app/'; // app source TS files
var appAssets = 'base/app/'; // component assets fetched by Angular's compiler
var testBase = 'testing/'; // transpiled test JS and map files
var testSrcBase = 'testing/'; // test source TS files
config.set({
basePath: '',
frameworks: ['jasmine'],
plugins: [
require('karma-jasmine'),
require('karma-chrome-launcher'),
require('karma-jasmine-html-reporter'), // click "Debug" in browser to see it
require('karma-htmlfile-reporter') // crashing w/ strange socket error
],
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',
'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},
{pattern: 'systemjs.config.extras.js', included: false, watched: false},
'karma-test-shim.js',
// transpiled application & spec code paths loaded via module imports
{pattern: appBase + '**/*.js', included: false, watched: true},
{pattern: testBase + '**/*.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: appSrcBase + '**/*.ts', included: false, watched: false},
{pattern: appBase + '**/*.js.map', included: false, watched: false},
{pattern: testSrcBase + '**/*.ts', included: false, watched: false},
{pattern: testBase + '**/*.js.map', included: false, watched: false}
],
// Proxied base paths for loading assets
proxies: {
// required for component assets fetched by Angular's compiler
"/app/": appAssets
},
exclude: [],
preprocessors: {},
// disabled HtmlReporter; suddenly crashing w/ strange socket error
reporters: ['progress', 'kjhtml'],//'html'],
// HtmlReporter configuration
htmlReporter: {
// Open this file to see results in browser
outputFile: '_test-output/tests.html',
// Optional
pageTitle: 'Unit Tests',
subPageTitle: __dirname
},
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ['Chrome'],
singleRun: false
})
}
**
systemjs.config.js
**
/**
* System configuration for Angular samples
* Adjust as necessary for your application needs.
*/
(function (global) {
System.config({
paths: {
// paths serve as alias
'npm:': 'node_modules/'
},
// map tells the System loader where to look for things
map: {
// our app is within the app folder
app: 'app',
// angular bundles
'#angular/core': 'npm:#angular/core/bundles/core.umd.js',
'#angular/common': 'npm:#angular/common/bundles/common.umd.js',
'#angular/compiler': 'npm:#angular/compiler/bundles/compiler.umd.js',
'#angular/platform-browser': 'npm:#angular/platform-browser/bundles/platform-browser.umd.js',
'#angular/platform-browser-dynamic': 'npm:#angular/platform-browser-dynamic/bundles/platform-browser-dynamic.umd.js',
'#angular/http': 'npm:#angular/http/bundles/http.umd.js',
'#angular/router': 'npm:#angular/router/bundles/router.umd.js',
'#angular/forms': 'npm:#angular/forms/bundles/forms.umd.js',
'#angular/upgrade': 'npm:#angular/upgrade/bundles/upgrade.umd.js',
// other libraries
'rxjs': 'npm:rxjs',
'angular2-google-maps/core': 'npm:angular2-google-maps/core/core.umd.js',
'angular-in-memory-web-api': 'npm:angular-in-memory-web-api',
'angular2-highcharts': 'npm:angular2-highcharts',
'highcharts/highstock.src': 'npm:highcharts/highstock.js',
'highcharts/highcharts-3d': 'npm:highcharts/highcharts-3d.js',
'highcharts': 'npm:highcharts',
'HighchartExporting': 'npm:highcharts/modules/exporting.js',
'HighchartCSVExporting': 'npm:highcharts/modules/export-csv.js',
'angular-2-local-storage': 'npm:angular-2-local-storage',
'angular2-logger': 'npm:angular2-logger',
'ng2-pagination': 'npm:ng2-pagination',
"ng2-modal": "node_modules/ng2-modal",
//'angular2-modal': 'npm:angular2-modal',
//'angular2-modal/plugins/bootstrap': 'npm:angular2-modal/plugins/bootstrap'
},
// packages tells the System loader how to load when no filename and/or no extension
packages: {
app: {
main: './main.js',
defaultExtension: 'js'
},
rxjs: {
defaultExtension: 'js'
},
'angular-in-memory-web-api': {
main: './index.js',
defaultExtension: 'js'
},
'angular2-highcharts': {
main: 'index',
format: 'cjs',
defaultExtension: 'js'
},
'highcharts': {
defaultExtension: 'js',
format: 'cjs'
},
'HighchartExporting': {
defaultExtension: 'js',
format: 'cjs'
},
'HighchartCSVExporting': {
defaultExtension: 'js',
format: 'cjs'
},
'angular-2-local-storage': { main: 'dist/index.js', defaultExtension: 'js' },
'angular2-logger': { main: 'core.js', defaultExtension: 'js' },
'ng2-pagination': {
main: 'index',
format: 'cjs',
defaultExtension: 'js'
},
"ng2-modal": { "main": "index.js", "defaultExtension": "js" },
//'angular2-modal': { defaultExtension: 'js', main: 'bundles/angular2-modal.umd' }
}
});
})(this);
**
app.component.spec.ts
**
/* tslint:disable:no-unused-variable */
import { AppComponent } from './app.component';
import { async, ComponentFixture, TestBed } from '#angular/core/testing';
import { By } from '#angular/platform-browser';
import { DebugElement } from '#angular/core';
//////// SPECS /////////////
describe('AppComponent', function () {
let de: DebugElement;
let deClick: DebugElement;
let comp: AppComponent;
let fixture: ComponentFixture<AppComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ AppComponent ]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(AppComponent);
comp = fixture.componentInstance;
de = fixture.debugElement.query(By.css('h1'));
debugger;
deClick=fixture.debugElement.query(By.css('input'));
});
it('should create component', () => expect(comp).toBeDefined() );
it('should have expected <h2> text', () => {
fixture.detectChanges();
const h1 = de.nativeElement;
expect(h1.innerText).toEqual('Hello Angular');
});
});
I am Following this tutorial on setting up a Webpack Angular 2 project.
I can run unit tests just fine with the setup, but I have tried adding code coverage to the project using karma-coverage and remap-istanbul, but it seems that karma-coverage is not outputting anything in the coverage-final.json.
What do I need to add to the karma config to get the test config to work?
Here is my current config:
var webpackConfig = require('./webpack.test');
module.exports = function (config) {
var _config = {
basePath: '',
frameworks: ['jasmine'],
files: [
{pattern: './config/karma-test-shim.js', watched: false}
],
preprocessors: {
'./config/karma-test-shim.js': ['webpack', 'sourcemap']
},
webpack: webpackConfig,
webpackMiddleware: {
stats: 'errors-only'
},
webpackServer: {
noInfo: true
},
reporters: ['progress'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: false,
browsers: ['PhantomJS'],
singleRun: true
};
config.set(_config);
};
You have two options, the easiest way is to use angular-cli. The hardest way is based on that tutorial make the changes needed for code coverage, which are a lot. One of the main things that you will be forced is to change to Webpack 2, I wasn't able to make awesome-typescript-loader work with karma using Webpack 1. The code coverage was always empty. I got some inspiration from angular-cli and from angular2-webpack-starter here are the changes:
karma.conf.js: add this:
remapIstanbulReporter: {
reports: {
html: 'coverage',
lcovonly: './coverage/coverage.lcov'
}
},
And change this:
reporters: ['progress'],
to this:
reporters: ['progress', 'karma-remap-istanbul'],
There are a lot of changes to the webpack configs so I'm just going to paste the entire config files, it's easier:
webpack.common.js:
var webpack = require('webpack');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var helpers = require('./helpers');
module.exports = {
entry: {
'polyfills': './src/polyfills.ts',
'vendor': './src/vendor.ts',
'app': './src/main.ts'
},
resolve: {
extensions: ['.ts', '.js']
},
module: {
rules: [
{
test: /\.ts$/,
loaders: ['awesome-typescript-loader', 'angular2-template-loader'],
exclude: [/\.(spec|e2e)\.ts$/]
},
{
test: /\.html$/,
loader: 'html'
},
{
test: /\.(png|jpe?g|gif|svg|woff|woff2|ttf|eot|ico)$/,
loader: 'file?name=assets/[name].[hash].[ext]'
},
{
test: /\.css$/,
exclude: helpers.root('src', 'app'),
loader: ExtractTextPlugin.extract({
fallbackLoader: 'style-loader',
loader: 'css-loader'
})
},
{
test: /\.css$/,
include: helpers.root('src', 'app'),
loader: 'raw'
}
]
},
plugins: [
new webpack.optimize.CommonsChunkPlugin({
// Optimizing ensures loading order in index.html
name: ['polyfills', 'vendor', 'app'].reverse()
}),
new webpack.optimize.CommonsChunkPlugin({
minChunks: Infinity,
name: 'inline',
filename: 'inline.js',
sourceMapFilename: 'inline.map'
}),
new HtmlWebpackPlugin({
template: 'src/index.html'
})
]
};
webpack.dev.js
var webpack = require('webpack');
var webpackMerge = require('webpack-merge');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var commonConfig = require('./webpack.common.js');
var helpers = require('./helpers');
module.exports = webpackMerge(commonConfig, {
devtool: 'cheap-module-eval-source-map',
output: {
path: helpers.root('dist'),
filename: '[name].js',
chunkFilename: '[id].chunk.js',
sourceMapFilename: '[name].map',
library: 'ac_[name]',
libraryTarget: 'var'
},
plugins: [
new webpack.LoaderOptionsPlugin({
options: {
tslint: {
emitErrors: false,
failOnHint: false,
resourcePath: 'src'
},
}
}),
new ExtractTextPlugin('[name].css')
],
devServer: {
historyApiFallback: true,
stats: 'minimal',
watchOptions: {
aggregateTimeout: 300,
poll: 1000
},
outputPath: helpers.root('dist')
},
node: {
global: true,
crypto: 'empty',
process: true,
module: false,
clearImmediate: false,
setImmediate: false
}
});
webpack.prod.js:
var webpack = require('webpack');
var webpackMerge = require('webpack-merge');
var WebpackMd5Hash = require('webpack-md5-hash');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var commonConfig = require('./webpack.common.js');
var helpers = require('./helpers');
const ENV = process.env.NODE_ENV = process.env.ENV = 'production';
module.exports = webpackMerge(commonConfig, {
devtool: 'source-map',
output: {
path: helpers.root('dist'),
filename: '[name].[chunkhash].js',
sourceMapFilename: '[name].[chunkhash].bundle.map',
chunkFilename: '[id].[chunkhash].chunk.js'
},
plugins: [
new WebpackMd5Hash(),
new webpack.NoErrorsPlugin(),
new webpack.optimize.UglifyJsPlugin({
mangle: { screw_ie8: true },
compress: { screw_ie8: true }
}),
new ExtractTextPlugin('[name].[hash].css'),
new webpack.DefinePlugin({
'process.env': {
'ENV': JSON.stringify(ENV)
}
}),
new webpack.LoaderOptionsPlugin({
options: {
tslint: {
emitErrors: true,
failOnHint: true,
resourcePath: helpers.root('src')
},
htmlLoader: {
minimize: true,
removeAttributeQuotes: false,
caseSensitive: true,
customAttrSurround: [
[/#/, /(?:)/],
[/\*/, /(?:)/],
[/\[?\(?/, /(?:)/]
],
customAttrAssign: [/\)?\]?=/]
}
}
}),
new webpack.ContextReplacementPlugin(
/angular(\\|\/)core(\\|\/)(esm(\\|\/)src|src)(\\|\/)linker/,
helpers.root('src')
)
],
node: {
fs: 'empty',
global: true,
crypto: 'empty',
process: true,
module: false,
clearImmediate: false,
setImmediate: false
}
});
webpack.test.js:
var helpers = require('./helpers');
var path = require('path');
var atl = require('awesome-typescript-loader');
var webpack = require('webpack');
module.exports = {
devtool: 'inline-source-map',
context: path.resolve(__dirname, './'),
resolve: {
extensions: ['.ts', '.js'],
plugins: [
new atl.TsConfigPathsPlugin({
tsconfig: helpers.root('tsconfig.json')
})
]
},
entry: {
test: helpers.root('config/karma-test-shim')
},
output: {
path: './dist.test',
filename: '[name].bundle.js'
},
module: {
rules: [
{
test: /\.ts$/,
enforce: 'pre',
loader: 'tslint-loader',
exclude: [
helpers.root('node_modules')
]
},
{
test: /\.js$/,
enforce: 'pre',
loader: 'source-map-loader',
exclude: [
helpers.root('node_modules/rxjs'),
helpers.root('node_modules/#angular')
]
},
{
test: /\.ts$/,
loaders: [
{
loader: 'awesome-typescript-loader',
query: {
tsconfig: helpers.root('tsconfig.json'),
module: 'commonjs',
target: 'es5',
useForkChecker: true
}
},
{
loader: 'angular2-template-loader'
}
],
exclude: [/\.e2e\.ts$/]
},
{
test: /\.html$/,
loader: 'html'
},
{
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: 'raw'
},
{
test: /\.(js|ts)$/, loader: 'sourcemap-istanbul-instrumenter-loader',
enforce: 'post',
exclude: [
/\.(e2e|spec)\.ts$/,
/node_modules/
],
query: { 'force-sourcemap': true }
},
]
},
plugins: [
new webpack.SourceMapDevToolPlugin({
filename: null, // if no value is provided the sourcemap is inlined
test: /\.(ts|js)($|\?)/i // process .js and .ts files only
}),
new webpack.LoaderOptionsPlugin({
options: {
tslint: {
emitErrors: false,
failOnHint: false,
resourcePath: `./src`
}
}
}),
new webpack.ContextReplacementPlugin(
/angular(\\|\/)core(\\|\/)(esm(\\|\/)src|src)(\\|\/)linker/,
helpers.root('src')
)
],
node: {
fs: 'empty',
global: true,
process: false,
crypto: 'empty',
module: false,
clearImmediate: false,
setImmediate: false
}
}
package.json:
You will need to install new packages and update your start script to this:
"start": "webpack-dev-server --config config/webpack.dev.js --profile --watch --content-base src/",
And install these packages:
npm i -D extract-text-webpack-plugin#2.0.0-beta.4 karma-remap-istanbul source-map-loader sourcemap-istanbul-instrumenter-loader tslint tslint-loader webpack#2.1.0-beta.25 webpack-dev-server#2.1.0-beta.3 webpack-md5-hash
Last but not least we just need to do some changes on the tsconfig.json and since we are now using tslint we add the a tslint.json file.
tsconfig.json:
{
"compilerOptions": {
"buildOnSave": false,
"compileOnSave": false,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"module": "commonjs",
"moduleResolution": "node",
"outDir": "dist/out-tsc",
"noImplicitAny": true,
"removeComments": false,
"sourceMap": true,
"suppressImplicitAnyIndexErrors": true,
"target": "es5"
}
}
tslint.json:
{
"rules": {
"member-access": false,
"member-ordering": [
true,
"public-before-private",
"static-before-instance",
"variables-before-functions"
],
"no-any": false,
"no-inferrable-types": false,
"no-internal-module": true,
"no-var-requires": false,
"typedef": false,
"typedef-whitespace": [
true,
{
"call-signature": "nospace",
"index-signature": "nospace",
"parameter": "nospace",
"property-declaration": "nospace",
"variable-declaration": "nospace"
},
{
"call-signature": "space",
"index-signature": "space",
"parameter": "space",
"property-declaration": "space",
"variable-declaration": "space"
}
],
"ban": false,
"curly": false,
"forin": true,
"label-position": true,
"label-undefined": true,
"no-arg": true,
"no-bitwise": true,
"no-conditional-assignment": true,
"no-console": [
true,
"debug",
"info",
"time",
"timeEnd",
"trace"
],
"no-construct": true,
"no-debugger": true,
"no-duplicate-variable": true,
"no-empty": false,
"no-eval": true,
"no-null-keyword": false,
"no-shadowed-variable": true,
"no-string-literal": false,
"no-switch-case-fall-through": true,
"no-unreachable": true,
"no-unused-expression": true,
"no-unused-variable": false,
"no-use-before-declare": true,
"no-var-keyword": true,
"radix": true,
"switch-default": true,
"triple-equals": [
true,
"allow-null-check"
],
"use-strict": [
true,
"check-module"
],
"eofline": true,
"indent": [
true,
"spaces"
],
"max-line-length": [
true,
100
],
"no-require-imports": false,
"no-trailing-whitespace": true,
"object-literal-sort-keys": false,
"trailing-comma": [
true,
{
"multiline": false,
"singleline": "never"
}
],
"align": false,
"class-name": true,
"comment-format": [
true,
"check-space"
],
"interface-name": false,
"jsdoc-format": true,
"no-consecutive-blank-lines": false,
"no-constructor-vars": false,
"one-line": [
true,
"check-open-brace",
"check-catch",
"check-else",
"check-finally",
"check-whitespace"
],
"quotemark": [
true,
"single",
"avoid-escape"
],
"semicolon": [true, "always"],
"variable-name": [
true,
"check-format",
"allow-leading-underscore",
"ban-keywords"
],
"whitespace": [
true,
"check-branch",
"check-decl",
"check-operator",
"check-separator",
"check-type"
]
}
}
If you want you can check the differences between the Angular.io setup (on the left) and the changes I made to make coverage work (on the right) here
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 am getting the Uncaught ReferenceError: require is not defined in jasmine unit test with karma.
this my karma.conf.js file.
tsconfig.json - target "target": "es6"
module.exports = function (config) {
config.set({
basePath: './',
frameworks: ['jasmine'],
files: [
'node_modules/reflect-metadata/Reflect.js',
'node_modules/systemjs/dist/system-polyfills.js',
'node_modules/systemjs/dist/system.src.js',
{ pattern: 'node_modules/rxjs/**/*.js', included: false, watched: false },
{ pattern: 'node_modules/rxjs/**/*.js.map', included: false, watched: false },
{ pattern: 'dist/dev/**/*.js', included: false, watched: true },
{ pattern: 'node_modules/systemjs/dist/system-polyfills.js', included: false, watched: false }, // PhantomJS2 (and possibly others) might require it
'dist/**/*.spec.js',
],
proxies: { },
exclude: [ ],
preprocessors: {
'dist/**/!(*spec).js': ['coverage']
},
reporters: ['mocha', 'coverage'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: [
'PhantomJS',
'Chrome'
],
singleRun: false,
client: { }
});
};
Recommend compiling your code with additionally --module commonjs and using a karma plugin that understands commonjs i.e. https://github.com/karma-runner/karma-commonjs