Angular 2 unit test compilation failed jasmine/karma - unit-testing

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/'
},

Related

Uncaught Syntax Error when running Vue.Js Unit Tests with Karma

I'm trying to get unit testing set up for my Vue JS project with Karma and Mocha (with vue-cli, I originally used Jest but I'm switching to Karma). I try to run my test with karma start; karma run and I keep getting:
09 03 2018 17:02:49.778:INFO [karma]: Karma v2.0.0 server started at http://0.0.0.0:9876/
09 03 2018 17:02:49.786:INFO [launcher]: Launching browser Chrome with unlimited concurrency
09 03 2018 17:02:49.797:INFO [launcher]: Starting browser Chrome
09 03 2018 17:02:54.410:INFO [Chrome 64.0.3282 (Windows 10.0.0)]: Connected on socket mvbOII8qli3NiwBMAAAA with id 62867001
Chrome 64.0.3282 (Windows 10.0.0) ERROR
{
"message": "Uncaught SyntaxError: Unexpected identifier\nat specs/PdfView.spec.js:3:8\n\nSyntaxError: Unexpected identifier",
"str": "Uncaught SyntaxError: Unexpected identifier\nat specs/PdfView.spec.js:3:8\n\nSyntaxError: Unexpected identifier"
}
The test runner starts, but I'm guessing some config issue is preventing the test from running properly. Also, it's not this just one component that will give me those errors.
My karma.conf.js file:
var webpackConfig = require('../../build/webpack.test.conf')
module.exports = function karmaConfig (config) {
config.set({
browsers: ['Chrome'],
frameworks: ['mocha'],
reporters: ['spec', 'coverage'],
files: ['specs/**/*.spec.js'],
preprocessors: {
'test/unit/spec/**/*.spec.js': [ 'webpack', 'sourcemap' ]
},
plugins: [
// Launchers
'karma-chrome-launcher',
// Test Libraries
'karma-mocha',
// 'karma-sinon-chai',
// Preprocessors
'karma-webpack',
'karma-sourcemap-loader',
// Reporters
'karma-spec-reporter',
'karma-coverage'
],
webpack: webpackConfig,
webpackMiddleware: {
noInfo: true
},
singleRun: true,
coverageReporter: {
dir: './coverage',
reporters: [
{ type: 'lcov', subdir: '.' },
{ type: 'text-summary' }
]
}
})
}
My .babelrc file:
{
"presets": [
["env", {
"modules": false,
"targets": {
"browsers": ["> 1%", "last 2 versions", "not ie <= 8"]
}
}],
"stage-2"
],
"plugins": ["transform-vue-jsx", "transform-runtime"],
"env": {
"test": {
"presets": ["env", "stage-2"],
"plugins": ["transform-vue-jsx", "transform-es2015-modules-commonjs", "dynamic-import-node"]
}
}
}
My webpack.test.conf.js:
'use strict'
const utils = require('./utils')
const webpack = require('webpack')
const merge = require('webpack-merge')
const baseWebpackConfig = require('./webpack.base.conf')
const webpackConfig = merge(baseWebpackConfig, {
// use inline sourcemap for karma-sourcemap-loader
module: {
rules: utils.styleLoaders(),
loaders: [
{
test: /\.js$/,
loader: 'babel-loader',
exclude: /node_modules/
},
{
test: /\.vue$/,
loader: 'vue-loader'
}
]
},
devtool: '#inline-source-map',
resolveLoader: {
alias: {
// necessary to to make lang="scss" work in test when using vue-loader's ?inject option
// see discussion at https://github.com/vuejs/vue-loader/issues/724
'scss-loader': 'sass-loader'
}
},
plugins: [
new webpack.DefinePlugin({
'process.env': require('../config/test.env')
})
]
})
delete webpackConfig.entry
module.exports = webpackConfig
PdfView.spec.js
import Vue from 'vue';
import Test from '#/components/Submission/PdfView';
describe('Test', () => {
it(`should render`, () => {
const Constructor = Vue.extend(Test);
const comp = new Constructor({}).$mount();
expect(comp.$el.textContent)
.to.equal('Test Text');
});
});
Webpack ^3.6.0,
Karma ^2.0.0,
Vue ^2.5.2
It looks to me like the # in import Test from '#/components/Submission/PdfView'; is not being resolved. Try adding this to your webpack.test.conf.js:
resolve: {
alias: {
'#': resolve('src')
}
}

Karma isn't suffixing the file with .js in angular 2 unit tests

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.

Angular2 Unit Test with Karma and Jasmin

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!

ReferenceError: Can't find variable: module or inject running unit-tests in test.js file

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

Testing a Controller using Jasmine in Karma

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 !