I'm struggling getting my Angular2 Unit Tests up and running.
I'm guessing it has something to do with my module loading.
This is the error I'm getting:
WARN [web-server]: 404:
/base/public/dev/assets/lib/node_modules/angular2/src/platform/browser/browser_adapter.js
Missing error handler on socket.
TypeError: (msg || "").replace is not a function
This is my karma.config.js
module.exports = function(config) {
config.set({
basePath: ".",
frameworks: ["jasmine"],
files: [
// paths loaded by Karma
{ pattern: "public/dev/assets/lib/node_modules/angular2/bundles/angular2-polyfills.js", included: true, watched: true },
{ pattern: "public/dev/assets/lib/node_modules/systemjs/dist/system.src.js", included: true, watched: true },
{ pattern: "public/dev/assets/lib/node_modules/rxjs/bundles/Rx.js", included: true, watched: true },
{ pattern: "public/dev/assets/lib/node_modules/angular2/bundles/angular2.dev.js", included: true, watched: true },
{ pattern: "public/dev/assets/lib/node_modules/angular2/bundles/testing.dev.js", included: true, watched: true },
{ pattern: "karma-test-shim.js", included: true, watched: true },
// paths loaded via module imports
{ pattern: "public/dev/assets/scripts/app/**/*.js", included: false, watched: true },
// paths to support debugging with source maps in dev tools
{ pattern: "public/dev/assets/scripts/app/**/*.ts", included: false, watched: false },
{ pattern: "public/dev/assets/scripts/app/**/*.js.map", included: false, watched: false }
],
// proxied base paths
proxies: {
// required for component assests fetched by Angular"s compiler
// Redirect all "/public/" paths to "/base/public" (Karma serves files from /base/)
"/public/": "/base/public/"
},
port: 9876,
logLevel: config.LOG_INFO,
colors: true,
autoWatch: true,
browsers: ["Chrome"],
// Karma plugins loaded
plugins: [
"karma-jasmine",
"karma-coverage",
"karma-chrome-launcher"
],
// Coverage reporter generates the coverage
reporters: ["progress", "dots", "coverage"],
// Source files that you wanna generate coverage for.
// Do not include tests or libraries (these files will be instrumented by Istanbul)
preprocessors: {
"public/dev/assets/scrips/app/**/!(*spec).js": ["coverage"]
},
coverageReporter: {
reporters:[
{type: "json", subdir: ".", file: "coverage-final.json"}
]
},
singleRun: true
})
};
This is my karma-test-shim.js
// Tun on full stack traces in errors to help debugging
Error.stackTraceLimit = Infinity;
jasmine.DEFAULT_TIMEOUT_INTERVAL = 1000;
// // Cancel Karma's synchronous start,
// // we will call `__karma__.start()` later, once all the specs are loaded.
__karma__.loaded = function() {};
System.config({
defaultJSExtensions: true,
map: {
angular2: "public/dev/assets/lib/node_modules/angular2",
rxjs: "public/dev/assets/lib/node_modules/rxjs"
},
packages: {
'base/public': {
format: 'register',
map: Object.keys(window.__karma__.files)
.filter(onlyAppFiles)
.reduce(createPathRecords, {})
}
}
});
System.import('angular2/src/platform/browser/browser_adapter')
.then(function(browser_adapter) { browser_adapter.BrowserDomAdapter.makeCurrent(); })
.then(function() { return Promise.all(resolveTestFiles()); })
.then(function() { __karma__.start(); }, function(error) { __karma__.error(error.stack || error); });
function createPathRecords(pathsMapping, appPath) {
// creates local module name mapping to global path with karma's fingerprint in path, e.g.:
// './vg-player/vg-player':
// '/base/dist/vg-player/vg-player.js?f4523daf879cfb7310ef6242682ccf10b2041b3e'
var pathParts = appPath.split('/');
var moduleName = './' + pathParts.slice(Math.max(pathParts.length - 2, 1)).join('/');
moduleName = moduleName.replace(/\.js$/, '');
pathsMapping[moduleName] = appPath + '?' + window.__karma__.files[appPath];
return pathsMapping;
}
function onlyAppFiles(filePath) {
return /\/base\/public\/dev\/assets\/(?!.*\.spec\.js$).*\.js$/.test(filePath);
}
function onlySpecFiles(path) {
return /\.spec\.js$/.test(path);
}
function resolveTestFiles() {
return Object.keys(window.__karma__.files) // All files served by Karma.
.filter(onlySpecFiles)
.map(function(moduleName) {
// loads all spec files via their global module names (e.g.
// 'base/dist/vg-player/vg-player.spec')
return System.import(moduleName);
});
}
As you can see I'm redirecting all /public/ paths to /base/public/ to handle the Karma default /base/ serving of files.
I double checked the path of the file that throws the 404, and it exists in the path provided (minus the /base/).
Can anyone point me in the right direction as to what may be going wrong here?
Thx!
Related
My project has the following structure:
two types of components, vue and folder with pug/js/styl;
index.pug is the main file that is to be index.html and index.pug extends layout and includes other pug, like head.pug that has the main.js script with imports of other required scripts. index.pug may also include a div container for main .vue component just like other .pug and .vue files are to be populated with either .vue or .pug components.
-index.pug <= layout,head .pug, main.vue, main.js, main.styl
-- .pug, .js, .styl folder-components
-- .vue components
I can not configure webpack properly to have index.html, error.html, /scripts/bundle.js, /styles/main.css
static-dist/index.html is empty or filled with JS code. So it cannot properly compile .pug and there is a mess with other parts related to vue, styl, pug. How to fix that all?
//const webpack = require('webpack');
const path = require('path');
const PugPlugin = require('pug-plugin');
const { VueLoaderPlugin, default: loader } = require('vue-loader')
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const CssMinimizerPlugin = require("css-minimizer-webpack-plugin");
const CopyPlugin = require("copy-webpack-plugin");
const threadLoader = require('thread-loader');
const autoprefixer = require('autoprefixer-stylus')
const devMode = process.env.NODE_ENV !== "production";
const PATHS = {
dist: path.resolve(__dirname, 'client-dist'),
};
threadLoader.warmup(
{
// pool options, like passed to loader options. must match loader options to boot the correct pool
},
[ // modules to load. can be any module, i. e.
'babel-loader',
'stylus-loader',
]
);
const config = {
entry: {
// The Pug file is the entry point for all scripts and styles. Source scripts and styles must be specified directly in Pug.
//error: './views/error.pug', // output to client-dist/index.html
index: './views/index.pug',
//script: path.join(__dirname + '/scripts/scripts.js'),
//'pages/page': './views/index.pug',
},
output: {
path: path.resolve('../client-dist'), //path.join(`${__dirname}`, `/../client-dist`),
filename: `scripts/bundle-[name].[contenthash:8].js`,
publicPath: '/' ,// public URL of the output directory when referenced in a browser
compareBeforeEmit: true, // true: will not write output file when file already exists on disk with the same content.
clean: true,
},
resolve: {
extensions: [".js", ".vue", ".css", "styl", "pug", "html"],
},
mode: 'development',
devtool: (devMode ? '#source-map' : false),
//devtool: 'eval-cheap-module-source-map',
cache: true,
module: {
rules: [
{
test: /\scripts.js$/,
exclude: file => ( /(node_modules|env_sr)/.test(file) && !/\.vue\.js/.test(file) ),
use: [
{
loader: 'babel-loader',
options: {
presets: ['#babel/preset-env'],
plugins: ['#babel/plugin-transform-runtime'],
cacheDirectory: true,
}
},
{
loader: 'thread-loader',
options: {
workers: 2,
}
},
{
loader: "source-map-loader",
//enforce: "pre"
},
]
},
/*{ loader: "style-loader", // creates style nodes from JS strings },
{ loader: "css-loader", // translates CSS into CommonJS
options: { sourceMap: true, }, },*/
{
test: /\.css$/i,
use: [ MiniCssExtractPlugin.loader, "vue-style-loader", "css-loader"], //, "stylus-loader"
},
{
test: /\.vue$/i,
use: ["vue-loader"]
},
{
test: /\.vue\.(styl)$/,///\.vue$/i,
sideEffects: true,
//loader: 'vue-loader',
use: ["vue-style-loader", "css-loader", {//"vue-loader",
loader: 'stylus-loader', options: {
stylusOptions: {
includeCSS: false,
resolveURL: true,
lineNumbers: false,
hoistAtrules: true,
compress: true,
sourceMap: true,
outputPath: "/styles/",
publicPath: "/styles/"
}
},
}, //autoprefixer(),z
], //, "stylus-loader"
},
{
test: /\.styl(us)?$/,
exclude: /node_modules/,
sideEffects: true,
use:
[
{ loader: 'resolve-url-loader' },
MiniCssExtractPlugin.loader,
//{ loader: 'vue-style-loader' },
{ loader: 'css-loader' },
//{ loader: 'resolve-url-loader' },
{
loader: 'stylus-loader',
options: {
stylusOptions: {
use: ["nib" /* , autoprefixer() */],
include: [path.join(__dirname, "styles/")],
import: ["nib", path.join(__dirname, "styles/helpers/*")],
define: [
["$development", process.env.NODE_ENV === "development"],
["$production", process.env.NODE_ENV === "production"],
],
includeCSS: false,
resolveURL: true,
lineNumbers: true,
hoistAtrules: true,
compress: true,
sourceMap: true,
outputPath: "/styles/",
publicPath: "/styles/"
}
},
}, autoprefixer(),
/*{ loader: "style-loader", }, { loader: "css-loader", }, { loader: "stylus-loader", }, */
] /* vue-style-loader', 'stylus-loader'], options: { stylusOptions: {} } */
},
{
test: /\.pug$/i,
exclude: /node_modules/,
loader: 'vue-pug-loader',//PugPlugin.loader, // PugPlugin already contain the pug-loader //'vue-pug-loader
oneOf: [
// this applies to `<template lang="pug">` in Vue components
{
resourceQuery: /^\?vue/,
use: ['pug-plain-loader'] // PugPlugin.loader
},
// this applies to pug imports inside JavaScript
//{ issuer: /\.(js)$/, use: ['raw-loader', 'pug-plain-loader'] },
{
use: [PugPlugin.loader
/* "html-loader",
"pug-html-loader" */
]
}
],
},
{
test: /\.(png|svg|jpg|gif)$/,
use: [
{
loader: 'file-loader', // resolves import/require() on a file into a url and emits the file into the output directory
options: {
name: '[name].[ext]',
outputPath: 'images',
},
}
],
},
{
test: /\.(ttf|eot|woff|woff2|svg)$/i,
use: {
loader: 'file-loader',
options: {
name: '[name].[ext]', // fonts/
outputPath: 'fonts',
publicPath: "fonts",
},
},
}
]
},
plugins: [
// enable processing of Pug files defined in webpack entry
new PugPlugin({
js: { filename: 'scripts/[name].[contenthash:8].js', },
css: { filename: './styles/[name].[contenthash:8].css', },
}),
new VueLoaderPlugin(),
new MiniCssExtractPlugin({filename: './styles/[name].[contenthash:8].css'}),
new CopyPlugin({
patterns: [
{ from: `${__dirname}/images`, to: `${__dirname}/../client-dist/images` },
{ from: `${__dirname}/icons`, to: `${__dirname}/../client-dist/icons` },
{ from: `${__dirname}/fonts`, to: `${__dirname}/../client-dist/fonts` },
{ from: `${__dirname}/data`, to: `${__dirname}/../client-dist/data` },
],
}),
],
optimization: {
minimizer: [
// For webpack#5 you can use the `...` syntax to extend existing minimizers (i.e. `terser-webpack-plugin`), uncomment the next line
// `...`,
new CssMinimizerPlugin({
parallel: true,
}),
],
}
};
if (!devMode) {
config.plugins.push(
// new UglifyJSPlugin(),
/* new CopyWebpackPlugin([{ from: __dirname + '/src/public' }]) */
);
};
/* if (process.env.NODE_ENV === 'test') {
module.exports.externals = [require('webpack-node-externals')()]
module.exports.devtool = 'inline-cheap-module-source-map'
} */
module.exports = config;
There is a minimum of html/js/css for dist/production static files and the rest is compiles on server and fetched upon a request, for instance, if "about" page is requested of a page component is to be loaded, a server gets a .vue or pug/js/styl page or component, compiles it and fetches the static code to client.
could somebody provide their thoughts about the error on compilation unit test for angular2 project?
14 04 2017 22:32:56.591:WARN [karma]: No captured browser, open http://localhost:9876/
14 04 2017 22:32:56.627:INFO [karma]: Karma v1.6.0 server started at http://0.0.0.0:9876/
14 04 2017 22:32:56.628:INFO [launcher]: Launching browser Chrome with unlimited concurrency
14 04 2017 22:32:56.678:INFO [launcher]: Starting browser Chrome
14 04 2017 22:33:00.850:INFO [Chrome 57.0.2987 (Windows 10 0.0.0)]: Connected on socket g9NBqcx7uGTZdJXBAAAA with id 58214193
14 04 2017 22:33:01.748:WARN [web-server]: 404: /base/systemjs.config.extras.js
14 04 2017 22:33:03.178:WARN [web-server]: 404: /base/node_modules/rxjs/RX.js
Chrome 57.0.2987 (Windows 10 0.0.0) ERROR
{
"originalErr": {}
}
My configuration are:
karma-test-shim.js
// #docregion
// /*global jasmine, __karma__, window*/
Error.stackTraceLimit = 0; // "No stacktrace"" is usually best for app testing.
// Uncomment to get full stacktrace output. Sometimes helpful, usually not.
//Error.stackTraceLimit = Infinity;
jasmine.DEFAULT_TIMEOUT_INTERVAL = 1000;
var builtPath = '/base/';
__karma__.loaded = function () { };
function isJsFile(path) {
return path.slice(-3) == '.js';
}
function isSpecFile(path) {
return /\.spec\.(.*\.)?js$/.test(path);
}
function isBuiltFile(path) {
return isJsFile(path) && (path.substr(0, builtPath.length) == builtPath);
}
var allSpecFiles = Object.keys(window.__karma__.files)
.filter(isSpecFile)
.filter(isBuiltFile);
System.config({
baseURL: 'base',
// Extend usual application package list with test folder
packages: { 'testing': { main: 'index.js', defaultExtension: 'js' } },
// Assume npm: is set in `paths` in systemjs.config
// Map the angular testing umd bundles
map: {
'#angular/core/testing': 'npm:#angular/core/bundles/core-testing.umd.js',
'#angular/common/testing': 'npm:#angular/common/bundles/common-testing.umd.js',
'#angular/compiler/testing': 'npm:#angular/compiler/bundles/compiler-testing.umd.js',
'#angular/platform-browser/testing': 'npm:#angular/platform-browser/bundles/platform-browser-testing.umd.js',
'#angular/platform-browser-dynamic/testing': 'npm:#angular/platform-browser-dynamic/bundles/platform-browser-dynamic-testing.umd.js',
'#angular/http/testing': 'npm:#angular/http/bundles/http-testing.umd.js',
'#angular/router/testing': 'npm:#angular/router/bundles/router-testing.umd.js',
'#angular/forms/testing': 'npm:#angular/forms/bundles/forms-testing.umd.js',
},
});
System.import('systemjs.config.js')
.then(importSystemJsExtras)
.then(initTestBed)
.then(initTesting);
/** Optional SystemJS configuration extras. Keep going w/o it */
function importSystemJsExtras(){
return System.import('systemjs.config.extras.js')
.catch(function(reason) {
console.log(
'Warning: System.import could not load the optional "systemjs.config.extras.js". Did you omit it by accident? Continuing without it.'
);
console.log(reason);
});
}
function initTestBed(){
return Promise.all([
System.import('#angular/core/testing'),
System.import('#angular/platform-browser-dynamic/testing')
])
.then(function (providers) {
var coreTesting = providers[0];
var browserTesting = providers[1];
coreTesting.TestBed.initTestEnvironment(
browserTesting.BrowserDynamicTestingModule,
browserTesting.platformBrowserDynamicTesting());
})
}
// Import all spec files and start karma
function initTesting () {
return Promise.all(
allSpecFiles.map(function (moduleName) {
return System.import(moduleName);
})
)
.then(__karma__.start, __karma__.error);
}
karma.conf.js
// Karma configuration
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. all assets served up at http://localhost/base/
config.set({
basePath: '',
frameworks: ['jasmine'],
plugins: [
require('karma-jasmine'),
require('karma-chrome-launcher'),
],
files: [
'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 },
'karma-test-shim.js',
// transpiled application & spec code paths loaded via module imports
{ pattern: appBase + '**/*.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 },
],
proxies: {
// required for component assets fetched by Angular's compiler
"/app/": appAssets
},
exclude: [
],
preprocessors: {
},
reporters: ['progress'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ['Chrome'],
singleRun: false,
concurrency: Infinity
})
}
systemjs.config.js
(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',
// other libraries
'rxjs': 'npm:rxjs'
},
// 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'
}
}
});
})(this);
If I tried to write a test for the component, I gather error above. Thank you.
Try adding the below property in the proxies Object so that you can alias the nodeModules folder with base added before it.
proxies: {
// required for component assets fetched by Angular's compiler
"/app/": appAssets,
"/node_modules":'/base/node_modules/'
},
i followed the instructions in quickstart and https://angular.io/docs/ts/latest/guide/testing.html but
Karma cannot load angular 2 component. getting this error,
404: /base/assets/components/app/myapp.component
file structure:
assets
| |components
| | |app
| | | |myapp.component.ts
| | | |myapp.component.spec.ts
| |systemjs.config.js
|karma.conf.js
|karma-test-shim.js
systemjs.config.js:
(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
myngapp: 'components/app',
myapp: 'components/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',
'#angular/upgrade/static': 'npm:#angular/upgrade/bundles/upgrade-static.umd.js',
// other libraries
'rxjs': 'npm:rxjs',
'angular-in-memory-web-api': 'npm:angular-in-memory-web-api/bundles/in-memory-web-api.umd.js',
'typescript': 'npm:typescript/lib/typescript.js'
},
transpiler: 'typescript',
typescriptOptions: {
emitDecoratorMetadata: true
},
// packages tells the System loader how to load when no filename and/or no extension
packages: {
myngapp: {
main: './main.ts',
defaultExtension: 'ts'
},
rxjs: {
defaultExtension: 'js'
}
}
});
})(this);
karma.conf.js:
module.exports = function(config) {
var appBase = 'assets/components/'; // transpiled app JS and map files
var appSrcBase = 'assets/components/'; // app source TS files
var appAssets = 'base/assets/components/app'; // component assets fetched by Angular's compiler
// Testing helpers (optional) are conventionally in a folder called `testing`
var testingBase = 'assets/components/'; // transpiled test JS and map files
var testingSrcBase = 'assets/components/'; // 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',
// 'assets/components/systemjs.config.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
// 'assets/components/systemjs.config.js',
{ 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
//'node_modules/#angular/**/*.js',
{ pattern: 'node_modules/#angular/**/*.js', included: false, watched: false },
{ pattern: 'node_modules/#angular/**/*.js.map', included: false, watched: false },
//'assets/components/systemjs.config.js',
{ pattern: 'assets/components/systemjs.config.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: 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: appSrcBase + '**/*.ts', included: false, watched: true },
{ pattern: appBase + '**/*.js.map', included: false, watched: false },
{ pattern: testingSrcBase + '**/*.ts', included: false, watched: true },
{ pattern: testingBase + '**/*.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: {},
reporters: ['progress', 'kjhtml'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ['Chrome'],
singleRun: false
})
}
karma-test-shim.js:
// /*global jasmine, __karma__, window*/
Error.stackTraceLimit = 0; // "No stacktrace"" is usually best for app testing.
// Uncomment to get full stacktrace output. Sometimes helpful, usually not.
// Error.stackTraceLimit = Infinity; //
jasmine.DEFAULT_TIMEOUT_INTERVAL = 1000;
// builtPaths: root paths for output ("built") files
// get from karma.config.js, then prefix with '/base/' (default is 'app/')
var builtPaths = (__karma__.config.builtPaths || ['assets/components/app/'])
.map(function(p) { return '/base/'+p;});
__karma__.loaded = function () { };
function isJsFile(path) {
return path.slice(-3) == '.js';
}
function isSpecFile(path) {
return /\.spec\.(.*\.)?js$/.test(path);
}
// Is a "built" file if is JavaScript file in one of the "built" folders
function isBuiltFile(path) {
return isJsFile(path) &&
builtPaths.reduce(function(keep, bp) {
return keep || (path.substr(0, bp.length) === bp);
}, false);
}
var allSpecFiles = Object.keys(window.__karma__.files)
.filter(isSpecFile)
.filter(isBuiltFile);
System.config({
baseURL: 'base',
// Extend usual application package list with test folder
packages: {
'testing': { main: 'main.js', defaultExtension: 'js' }
},
// Assume npm: is set in `paths` in systemjs.config
// Map the angular testing umd bundles
map: {
'#angular/core/testing': 'npm:#angular/core/bundles/core-testing.umd.js',
'#angular/common/testing': '.npm:#angular/common/bundles/common-testing.umd.js',
'#angular/compiler/testing': 'npm:#angular/compiler/bundles/compiler-testing.umd.js',
'#angular/platform-browser/testing': 'npm:#angular/platform-browser/bundles/platform-browser-testing.umd.js',
'#angular/platform-browser-dynamic/testing': 'npm:#angular/platform-browser-dynamic/bundles/platform-browser-dynamic-testing.umd.js',
'#angular/http/testing': 'npm:#angular/http/bundles/http-testing.umd.js',
'#angular/router/testing': 'npm:#angular/router/bundles/router-testing.umd.js',
'#angular/forms/testing': 'npm:#angular/forms/bundles/forms-testing.umd.js',
},
});
System.import('assets/components/systemjs.config.js')
.then(initTestBed)
.then(initTesting);
/** Optional SystemJS configuration extras. Keep going w/o it */
/*function importSystemJsExtras(){
return System.import('systemjs.config.extras.js')
.catch(function(reason) {
console.log(
'Warning: System.import could not load the optional "systemjs.config.extras.js". Did you omit it by accident? Continuing without it.'
);
console.log(reason);
});
}*/
//initTestBed();
//initTesting();
function initTestBed(){
return Promise.all([
System.import('#angular/core/testing'),
System.import('#angular/platform-browser-dynamic/testing')
])
.then(function (providers) {
var coreTesting = providers[0];
var browserTesting = providers[1];
coreTesting.TestBed.initTestEnvironment(
browserTesting.BrowserDynamicTestingModule,
browserTesting.platformBrowserDynamicTesting());
})
}
// Import all spec files and start karma
function initTesting () {
return Promise.all(
allSpecFiles.map(function (moduleName) {
return System.import(moduleName);
})
)
.then(__karma__.start, __karma__.error);
}
If i go to the compile js file of my test (myapp.component.spec.js) and change the import from myapp.component to myapp.component.js, test runs successfully. given example below,
eg:
when compiled by angular myapp.component.spec.js looks like,
var myapp_component_1 = require('./myapp.component');
i update it to
var myapp_component_1 = require('./myapp.component.js');
and test runs
i do not know why it cannot find the component even though the path is correct. Please help.
I'm getting an error in my terminal output from PhantomJS ReferenceError: Can't find variable: module in www/signin/tests/signin.service.tests.js and ReferenceError: Can't find variable: inject in www/signin/tests/signin.service.tests.js where they are called in the code below.
describe('signinService', function(){
var controller,
deferredSigin,
signinServiceMock,
stateMock,
hasClass = function (element, cls) {
return element.getAttribute('class').then(function (classes) {
return classes.split(' ').indexOf(cls) !== -1;
});
};
beforeEach(function(){
module('app');
});
// disable template caching
beforeEach(module(function($provide, $urlRouterProvider) {
$provide.value('$ionicTemplateCache', function(){} );
$urlRouterProvider.deferIntercept();
}));
beforeEach(inject(function($controller, $q){
deferredSigin = $q.defer();
signinServiceMock = {
signin: jasmine.createSpy('signin spy').and.returnValue(deferredSigin.promise)
};
stateMock = jasmine.creatSpyObj('$state spy', ['go']);
controller = $controller('SiginController', {
'$state': stateMock,
'signinService': signinServiceMock
});
}));
I have my unit-test.conf.js in the root of my application with file paths configured as shown
module.exports = function(config) {
config.set({
basePath: '',
frameworks: ['jasmine'],
files: [
'www/lib/angular/angular.min.js',
'www/lib/angular-mocks/angular-mocks.js',
'www/app.js',
'www/signin/services/*.js',
'www/signin/*.js',
'www/signin/tests/*.js'
],
exclude: [
],
preprocessors: {
},
reporters: ['progress'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ['PhantomJS'],
singleRun: false,
concurrency: Infinity
});
};
I was following this tutorial. It seems like angular-mocks isn't getting loaded. Not sure why. I'm passing it in the files in unit-test.conf.js
I'm trying to test a controller but I'm getting an error
TypeError: Object # has no method 'apply' ReferenceError:
inject is not defined
The unit-test.js is
define(['angular',
'myApp',
'angularMocks',
'MyCtrl'
], function() {
describe('Testing controller', function() {
var $scope = null;
var ctrl = null;
beforeEach(angular.module('myApp'));
beforeEach(inject(function ($injector) {
$scope = $injector.get('$rootScope');
$controller = $injector.get('$controller');
}));
describe('MyCtrl', function () {
it('should call test variable', function () {
$scope = $rootScope.$new();
ctrl = $controller('MyCtrl', {
$scope: $scope
});
expect($scope.test).toBe("sth");
});
});
});
});
in MyCtrl I have declared a $scope.test = "sth";
When I change
beforeEach(angular.module('myApp')); to beforeEach(module('myApp'));
I'm getting ReferenceError: module is not defined
I use Karma version: 0.9.8 and AngularJS v1.0.8
Thank you very much!
You have a lot of things to do if you're using requirejs.
First you have to put the karma-requirejs plugin in your package.json
"karma-requirejs": "~0.1.0",
Then you have ti change your config file. You have to add requirejs in frameworks part
Then exclude your require main.js
Then add all your librairies files via the pattern config and not include it
You have to add your require main-test.js (config file for test describe at bottom)
module.exports = function (config) {
config.set({
basePath: '',
frameworks: ['jasmine', 'requirejs'],
files: [
{pattern: 'app/bower_components/jquery/jquery.min.js', included: false},
{pattern: 'app/bower_components/angular/angular.min.js', included: false},
{pattern: 'app/bower_components/angular-resource/angular-resource.min.js', included: false},
{pattern: 'app/bower_components/angular-mocks/angular-mocks.js', included: false},
{pattern: 'app/scripts/*.js', included: false},
{pattern: 'app/scripts/**/*.js', included: false},
{pattern: 'test/spec/**/*Spec.js', included: false},
'test/main-test.js'
],
exclude: ['app/scripts/main.js'],
port: 8082,
logLevel: config.LOG_DEBUG,
autoWatch: false,
browsers: ['Chrome'],
singleRun: false
});
};
Now create your main-test.js.
In you have to get all your tests files to put it as dependencies.
Then do a classic requirejs config (note in the baseUrl we use /base a karma constant) and finally start karma by code through : window.__karma__.start();
Example :
var tests = [];
for (var file in window.__karma__.files) {
if (window.__karma__.files.hasOwnProperty(file)) {
if (/Spec\.js$/.test(file)) {
tests.push(file);
}
}
}
require.config({
// Karma serves files from '/base'
baseUrl: '/base/app/scripts',
paths: {
jquery: '../bower_components/jquery/jquery.min',
angular: '../bower_components/angular/angular.min',
angularMocks: '../bower_components/angular-mocks/angular-mocks',
ngResource: '../bower_components/angular-resource/angular-resource.min'
},
shim: {
jquery: {
exports: '$'
},
angular: {
deps: [ 'jquery', 'bootstrap'],
exports: 'angular'
},
ngResource: {
deps: [ 'angular' ],
exports: 'ngResource'
},
angularMocks: {
deps: [ 'ngResource' ],
exports: 'angularMocks'
}
},
priority: [
'angular'
],
// ask Require.js to load these files (all our tests)
deps: tests
});
require(tests, function(){
window.__karma__.start();
});
In your test file :
change beforeEach(angular.module('myApp')); to beforeEach(module('myApp'));
Change the params of your define like that :
define(['angular',
'myApp',
'angularMocks',
'MyCtrl'
], function(angular, myApp, angularMocks, MyCtrl)
To inject controller just do that (You have to put the MyCtrl in param of your require function) :
beforeEach(inject(function ($controller, $rootScope) {
scope = $rootScope.$new();
$controller(MyCtrl, {
$scope: scope
});
}));
And finally :
it('should call crudListMethods', function () {
expect(scope.test).toBe("sth");
});
Now it should work ! Hope it helps !