karma test cases are running multiple times: Angular unit test - unit-testing

I am not able to understand why my karma test cases re runs multiple times after a fixed test case.
Disconnected, because no message in 50000 ms.
Chrome 75.0.3770 (Windows 10.0.0): Executed 131 of 251 DISCONNECTED (1 min 9.028 secs / 18.285 secs)
Chrome 75.0.3770 (Windows 10.0.0): Executed 131 of 251 DISCONNECTED (47.273 secs / 18.169 secs)
Chrome 75.0.3770 (Windows 10.0.0): Executed 131 of 251 DISCONNECTED (1 min 9.028 secs / 18.285 secs)
Chrome 75.0.3770 (Windows 10.0.0): Executed 131 of 251 DISCONNECTED (47.273 secs / 18.169 secs)
Chrome 75.0.3770 (Windows 10.0.0): Executed 97 of 251 DISCONNECTED (22.07 secs / 19.87 secs)
Chrome 75.0.3770 (Windows 10.0.0): Executed 131 of 251 DISCONNECTED (1 min 9.028 secs / 18.285 secs)
Chrome 75.0.3770 (Windows 10.0.0): Executed 131 of 251 SUCCESS (0 secs / 17.406 secs)
Chrome 75.0.3770 (Windows 10.0.0): Executed 239 of 251 SUCCESS (0 secs / 20.912 secs)
Below is the configuration of karma.conf.js
// Karma configuration file, see link for more information
// https://karma-runner.github.io/1.0/config/configuration-file.html
const { join } = require('path');
const { constants } = require('karma');
module.exports = () => {
return {
basePath: '',
frameworks: ['jasmine', '#angular-devkit/build-angular'],
plugins: [
require('karma-jasmine'),
require('karma-chrome-launcher'),
require('karma-jasmine-html-reporter'),
require('karma-coverage-istanbul-reporter'),
require('#angular-devkit/build-angular/plugins/karma')
],
client: {
clearContext: false, // leave Jasmine Spec Runner output visible in browser
jasmine: {
random: false
}
},
coverageIstanbulReporter: {
dir: join(__dirname, '../../coverage'),
reports: ['html', 'lcovonly'],
fixWebpackSourcePaths: true
},
reporters: ['progress', 'kjhtml'],
port: 9876,
colors: true,
logLevel: constants.LOG_INFO,
autoWatch: true,
browsers: ['Chrome'],
singleRun: true,
};
};
when I change singleRun to false and execute test case using ng test, it works fine, the problem is only when I change it to true.
I saw couple of blogs and tried to resolve it by adding some more configuration like
browserNoActivityTimeout: 50000,
captureTimeout: 60 * 1000,
// captureTimeout: 210000,
browserDisconnectTolerance: 1,
// browserDisconnectTimeout: 210000,
// browserNoActivityTimeout: 210000
but nothing has worked for me.
Below is the configuration in devDependencies (I am using angular cli version 8)
"devDependencies": {
"#angular-devkit/build-angular": "0.800.3",
"#angular-devkit/build-ng-packagr": "0.800.3",
"#angular/cli": "^8.0.3",
"#angular/compiler-cli": "~8.0.0",
"#angular/language-service": "^6.1.0",
"#ngrx/store-devtools": "6.0.1",
"#nrwl/schematics": "~8.0.0",
"#ruf/schematics": "next",
"#ruf/wrench": "next",
"#types/jasmine": "~2.8.6",
"#types/jasminewd2": "~2.0.3",
"#types/node": "^8.10.10",
"codelyzer": "5.1.0",
"dotenv": "6.2.0",
"jasmine-core": "~3.4.0",
"jasmine-marbles": "0.3.1",
"jasmine-spec-reporter": "~4.2.1",
"karma": "~4.1.0",
"karma-chrome-launcher": "~2.2.0",
"karma-coverage-istanbul-reporter": "^2.0.5",
"karma-jasmine": "~2.0.1",
"karma-jasmine-html-reporter": "~1.4.2",
"ngrx-store-freeze": "0.2.4",
"prettier": "1.16.4",
"protractor": "~5.3.0",
"scss-bundle": "^2.1.2",
"ts-node": "~7.0.0",
"tslint": "~5.11.0",
"typescript": "~3.4.5",
"istanbul-instrumenter-loader": "^3.0.1",
"karma-sourcemap-loader": "^0.3.7",
"karma-webpack": "^3.0.4",
"source-map-loader": "^0.2.4"
}
Please suggest !!!!

I fixed the above issue by spying on functions which has location.href set inside it.
location.href was causing the page to load with different URL and because of that karma was running again and again.

Related

Karma+Jasmine tests not running with Chrome, "Executed 0 of 0 ERROR"

I'm trying to test my project angular 5 with jasmine and karma but it show me this error:
myProject\Front\src\app> ng test
Your global Angular CLI version (7.0.3) is greater than your local
version (1.7.4). The local Angular CLI version is used.
To disable this warning use "ng config -g cli.warnings.versionMismatch false".
30 10 2018 09:42:25.435:WARN [karma]: No captured browser, open http://localhost:9876/
30 10 2018 09:42:38.011:INFO [karma]: Karma v0.13.9 server started at http://localhost:9876/
30 10 2018 09:42:38.016:INFO [launcher]: Starting browser Chrome
30 10 2018 09:42:41.074:INFO [Chrome 69.0.3497 (Windows 10 0.0.0)]: Connected on socket RiQkM_n-0oc-xuYAAAAA with id 49828596
Chrome 69.0.3497 (Windows 10 0.0.0) ERROR: 'DEPRECATION:', 'Setting specFilter directly on Env is deprecated, please use the specFilter option in `configure`'
Chrome 69.0.3497 (Windows 10 0.0.0): Executed 0 of 0 ERROR (0.003 secs / 0 secs)
and this is my karma.conf.js :
// Karma configuration
// Generated on Mon Oct 29 2018 16:09:43 GMT+0000 (Maroc)
module.exports = function (config) {
config.set({
// base path that will be used to resolve all patterns (eg. files, exclude)
basePath: '',
// frameworks to use
// available frameworks: https://npmjs.org/browse/keyword/karma-adapter
frameworks: ['jasmine'],
//plugin needed
plugins: [
require('karma-jasmine'),
require('karma-chrome-launcher'),
require('karma-jasmine-html-reporter'),
require('karma-coverage-istanbul-reporter'),
],
// list of files / patterns to load in the browser
files: [
'src/app/*.spec.ts',
],
// list of files / patterns to exclude
exclude: [
],
// preprocess matching files before serving them to the browser
// available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
preprocessors: {
},
// test results reporter to use
// possible values: 'dots', 'progress'
// available reporters: https://npmjs.org/browse/keyword/karma-reporter
reporters: ['progress'],
// web server port
port: 9876,
// enable / disable colors in the output (reporters and logs)
colors: true,
// level of logging
// possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
logLevel: config.LOG_INFO,
// enable / disable watching file and executing tests whenever any file changes
autoWatch: true,
// start these browsers
// available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
browsers: ['Chrome'],
// Continuous Integration mode
// if true, Karma captures browsers, runs the tests and exits
singleRun: false,
// Concurrency level
// how many browser should be started simultaneous
concurrency: Infinity
})
}
and this the interface in Google Chrome:
I'm just a beginner 😄 and I'm not sure if those informations are enough. I tried a lot of solutions that I found but always the same problem. Can someone help me?
This is a result of an incompatibility with newer versions of Chrome (failing for me with version 70) and the newest version of jasmine (3.3.0). The short term workaround is to lock your jasmine-core version to 3.2.0.

Karma tests fail with Browser DISCONNECTED error, exit code: 1

We have a total of 2016 unit test cases written with Jasmine and are using Karma to run them. The tests run for a period of 1 min 30 sec to 2 min and then suddenly Karma disconnects from the browser.Here is a screenshot of the console logs.
The problem is that I am not able to diagnose why that is happening and which test case is causing it to get disconnected. I have tried different reporters of Karma to be able to identify the test case which forces it to disconnect from the browser but have been unsuccessful so far.
I have also tried running the tests in short batches to be able to drill down to the error test case (in case it is a test case error and not Karma configuration) but so far, the error has been thrown for all batches.
As per this post, I have tried setting the browserNoActivityTimeout to as high as 10 minutes (600000ms) but still no resolution. Also, the post mentions that there might be a problem with insufficient memory, so I have tried running the cases in one 8GB RAM and one 16GB RAM systems (Windows 10 on both).
Here's the complete stack trace:
[02:06:48] Error: MyApp Chromebook Unit tests failed with exitCode: 1
at formatError (C:\Users\barnadeep.bhowmik\AppData\Roaming\npm\node_modules\gulp\bin\gulp.js:169:10)
at Gulp.<anonymous> (C:\Users\barnadeep.bhowmik\AppData\Roaming\npm\node_modules\gulp\bin\gulp.js:195:15)
at emitOne (events.js:96:13)
at Gulp.emit (events.js:188:7)
at Gulp.Orchestrator._emitTaskDone (C:\Users\barnadeep.bhowmik\Desktop\Projects\MyProject\test-player-15-may\myapp-chrome\node_modules\orchestrator\index.js:264:8)
at C:\Users\barnadeep.bhowmik\Desktop\Projects\MyProject\test-player-15-may\myapp-chrome\node_modules\orchestrator\index.js:275:23
at finish (C:\Users\barnadeep.bhowmik\Desktop\Projects\MyProject\test-player-15-may\myapp-chrome\node_modules\orchestrator\lib\runTask.js:21:8)
at cb (C:\Users\barnadeep.bhowmik\Desktop\Projects\MyProject\test-player-15-may\myapp-chrome\node_modules\orchestrator\lib\runTask.js:29:3)
at C:\Users\barnadeep.bhowmik\Desktop\Projects\MyProject\test-player-15-may\myapp-chrome\build\tasks\test.js:18:13
at removeAllListeners (C:\Users\barnadeep.bhowmik\Desktop\Projects\MyProject\test-player-15-may\myapp-chrome\node_modules\karma\lib\server.js:336:7)
at Server.<anonymous> (C:\Users\barnadeep.bhowmik\Desktop\Projects\MyProject\test-player-15-may\myapp-chrome\node_modules\karma\lib\server.js:347:9)
at Server.g (events.js:291:16)
at emitNone (events.js:91:20)
at Server.emit (events.js:185:7)
at emitCloseNT (net.js:1555:8)
at _combinedTickCallback (internal/process/next_tick.js:71:11)
at process._tickCallback (internal/process/next_tick.js:98:9)
Here's my config file:
module.exports = function(config) {
config.set({
basePath: '',
frameworks: ['jasmine'],
files: [
'bower_components/jquery/dist/jquery.js',
'node_modules/angular/angular.js',
'other_dependencies/**.*.js',
'src/app/app.js',
'src/app/pack1-components/**/*.js',
'src/app/pack2-components/**/*.js',
'src/**/*.html'
],
exclude: [
'src/some-folder/*',
],
port: 8081,
logLevel: config.LOG_INFO,
autoWatch: false,
browsers: ['ChromeNoSandbox'],//temp fix for Chrome Browser 'Chrome'
customLaunchers: {
ChromeNoSandbox: {
base: 'Chrome',
flags: ['--no-sandbox']
}
},
reporters: ["spec","progress","coverage","html"],
specReporter: {
maxLogLines: 5, // limit number of lines logged per test
suppressErrorSummary: false, // do not print error summary
suppressFailed: false, // do not print information about failed tests
suppressPassed: false, // do not print information about passed tests
suppressSkipped: true, // do not print information about skipped tests
showSpecTiming: false, // print the time elapsed for each spec
failFast: true // test would finish with error when a first fail occurs.
},
preprocessors: {
'src/**/*.js':['coverage'],
'src/**/*.html':['ng-html2js']
},
coverageReporter: {
type: 'lcov',
dir: 'qualityreports/testresults/unit/coverage/'
},
htmlReporter: {
outputFile: 'qualityreports/testresults/unit/testresults.html'
},
browserNoActivityTimeout: 600000,
captureTimeout: 60000,
browserDisconnectTimeout : 60000,
browserDisconnectTolerance : 1,
ngHtml2JsPreprocessor: {
},
plugins: [
'karma-jasmine','karma-chrome-launcher','karma-coverage','karma-htmlfile-reporter','karma-ng-html2js-preprocessor',"karma-spec-reporter"],
singleRun: true
});
};
Here is a similar post but it did not have all details, hence posting mine. Any help would be deeply appreciated.

beforeEach fails in karma + Mocha with angular 4 upgrade

Context
I have confirmed "green" builds on the master branch which is using angular-cli 1.0.0 and the old angular2 dependencies. My Objective is to upgrade from angular2 to angular4.
Post upgrade issue
The application works
The unit tests fail in karma using ng test and npm run test which are equivalent
Working configuration
specifically the package.json is as follows.
...
"dependencies": {
"#angular/common": "^2.4.0",
"#angular/compiler": "^2.4.0",
"#angular/core": "^2.4.0",
"#angular/forms": "^2.4.0",
"#angular/http": "^2.4.0",
"#angular/platform-browser": "^2.4.0",
"#angular/platform-browser-dynamic": "^2.4.0",
"#angular/router": "^3.4.0",
...
},
"devDependencies": {
"#angular/cli": "1.0.0",
"#angular/compiler-cli": "^2.4.0",
...
}
With the following test result
Chromium 53.0.2785 (Ubuntu 0.0.0): Executed 82 of 83 (skipped 1) SUCCESS (5.674 secs / 0.061 secs)
Angular 4 upgrade fails the tests
When I try to upgrade the angular4 dependencies with a very specific diff the application runs successfully, however I get failed/repeated tests for the upgrade like so Chromium 53.0.2785 (Ubuntu 0.0.0): Executed 127 of 83 (32 FAILED) (skipped 2) (7.521 secs / 0.101 secs)
What I find fascinating about the result is that there are 44 tests run in addition to the number of tests I actually have. It also appears that the only tests that fail are the duplicate tests that are running and they fail directly after they succeed. On investigation is seems that these tests would fail if their before each were not run
Chrome 56.0.2924 (Linux 0.0.0): Executed 67 of 83 (13 FAILED) (0 secs / 0.11 secs)
✔ will raise a houseCreated event
Chrome 56.0.2924 (Linux 0.0.0) HouseListComponent when valid input is provided (while in create mode) will raise a houseCreated event FAILED
AssertionError: expected { Object (country, state, ...) } to equal { Object (country, state, ...) }
at Context.<anonymous> (webpack:///src/app/housing/components/edit/house-edit.component.spec.ts:69:40 <- src/test.ts:26683:54)
at ZoneDelegate.invoke (webpack:///~/zone.js/dist/zone.js:365:0 <- src/polyfills.ts:1520:26)
at ProxyZoneSpec.Array.concat.ProxyZoneSpec.onInvoke (webpack:///~/zone.js/dist/proxy.js:79:0 <- src/test.ts:88673:39)
at ZoneDelegate.invoke (webpack:///~/zone.js/dist/zone.js:364:0 <- src/polyfills.ts:1519:32)
at Zone.run (webpack:///~/zone.js/dist/zone.js:125:0 <- src/polyfills.ts:1280:43)
at Context.<anonymous> (webpack:///~/zone.js/dist/mocha-patch.js:88:0 <- src/test.ts:88521:33)
at webpack:///~/zone.js/dist/mocha-patch.js:140:0 <- src/test.ts:88573:33
at ZoneDelegate.invokeTask (webpack:///~/zone.js/dist/zone.js:398:0 <- src/polyfills.ts:1553:31)
at Zone.runTask (webpack:///~/zone.js/dist/zone.js:165:0 <- src/polyfills.ts:1320:47)
at drainMicroTaskQueue (webpack:///~/zone.js/dist/zone.js:593:0 <- src/polyfills.ts:1748:35)
at ZoneTask.invoke (webpack:///~/zone.js/dist/zone.js:464:0 <- src/polyfills.ts:1619:25)
at timer (webpack:///~/zone.js/dist/zone.js:1540:0 <- src/polyfills.ts:2695:29)
Chrome 56.0.2924 (Linux 0.0.0): Executed 68 of 83 (14 FAILED) (0 secs / 0.111 secs)
✖ will raise a houseCreated event
broken configuration
...
"dependencies": {
"#angular/common": "^4.0.1",
"#angular/compiler": "^4.0.1",
"#angular/core": "^4.0.1",
"#angular/forms": "^4.0.1",
"#angular/http": "^4.0.1",
"#angular/platform-browser": "^4.0.1",
"#angular/platform-browser-dynamic": "^4.0.1",
"#angular/router": "^4.0.1",
...
},
"devDependencies": {
"#angular/cli": "1.0.0",
"#angular/compiler-cli": "^4.0.1",
...
}
Same tests on a different runner
In attempt to identify if the issue was the tests or the runner, I ran the exact same tests with the wallabyjs runner and I get No failing tests, 82 passing which is perfectly inline with master using the upgraded angular4 dependencies. This would seem to indicate that the issues is specific to karma and not the tests.
resources
Working master
Broken branch
Errors
There are a number of test errors, however they all seem to be related to beforeEach. The test module should not already be instantiated which seems to be a weird side effect from the repeating tests.
Chrome 56.0.2924 (Linux 0.0.0) car reducer "before each" hook for "will return array removes existing values when state is not empty" FAILED
Error: Cannot configure the test module when the test module has already been instantiated. Make sure you are not using `inject` before `TestBed.configureTestingModule`.
at TestBed.Array.concat.TestBed._assertNotInstantiated (webpack:///~/#angular/core/#angular/core/testing.es5.js:749:0 <- src/test.ts:25844:19) [ProxyZone]
at TestBed.Array.concat.TestBed.configureTestingModule (webpack:///~/#angular/core/#angular/core/testing.es5.js:671:0 <- src/test.ts:25766:14) [ProxyZone]
at Function.Array.concat.TestBed.configureTestingModule (webpack:///~/#angular/core/#angular/core/testing.es5.js:576:0 <- src/test.ts:25671:22) [ProxyZone]
at Context.<anonymous> (webpack:///src/app/car/reducers/car.reducer.spec.ts:30:12 <- src/test.ts:31440:27) [ProxyZone]
at ProxyZoneSpec.Array.concat.ProxyZoneSpec.onInvoke (webpack:///~/zone.js/dist/proxy.js:79:0 <- src/test.ts:88673:39) [ProxyZone]
at Zone.run (webpack:///~/zone.js/dist/zone.js:125:0 <- src/polyfills.ts:1280:43) [<root> => ProxyZone]
at Context.<anonymous> (webpack:///~/zone.js/dist/mocha-patch.js:88:0 <- src/test.ts:88521:33) [<root>]
Then after the before each fails then we get more errors regarding the property call
Chrome 56.0.2924 (Linux 0.0.0) car reducer "before each" hook for "will return array removes existing values when state is not empty" FAILED
TypeError: Cannot read property 'call' of undefined
at ZoneDelegate.invokeTask (webpack:///~/zone.js/dist/zone.js:398:0 <- src/polyfills.ts:1553:31)
at Zone.runTask (webpack:///~/zone.js/dist/zone.js:165:0 <- src/polyfills.ts:1320:47)
at ZoneTask.invoke (webpack:///~/zone.js/dist/zone.js:460:0 <- src/polyfills.ts:1615:38)
at timer (webpack:///~/zone.js/dist/zone.js:1540:0 <- src/polyfills.ts:2695:29)
Chrome 56.0.2924 (Linux 0.0.0): Executed 45 of 83 (8 FAILED) (0 secs / 0.092 secs)
Multiple references in the frameworks array should be avoided with Karma. Use the plugins instead
This issue around the failing beforeEach was actually a red herring and a side effect of the repeating tests. It appears that the life cycle being executed was:
beforeEach
it('myTest1') pass
it('myTest1') fail
beforeEach
it('myTest2') pass
it('myTest2') fail
If we stop the tests repeating then the beforeEach issue doesn't actually exist. This was digested and demonstrated in a karma issue which turned out to be user (my) error.
To stop the tests repeating we needed to update the frameworks array in the karma.conf.js and reduce the number of framework references and use the plugins instead which were already referenced.
frameworks: ['mocha', 'chai', 'sinon-chai', '#angular/cli'],
becomes
frameworks: ['mocha', '#angular/cli'],
Resolution
Stop the tests repeating and the beforeEach will behave as expected. A working commit can be found here.

Karma run test cases double times

I am using karma for angular 2 unit testing.Its works fine to me but I have one thing which I don't know why its happening.With karma when I run test cases, every function which I test run two times.I knew this problem when I print console.log on that function which I used in test case.I don't know why this happened to me.Please help me.
I am using it with webpack.
webpack: bundle is now VALID.
17 10 2016 10:02:20.102:INFO [karma]: Karma v1.2.0 server started at http://localhost:9876/
17 10 2016 10:02:20.106:INFO [launcher]: Launching browser Chrome with unlimited concurrency
17 10 2016 10:02:20.188:INFO [launcher]: Starting browser Chrome
17 10 2016 10:02:40.019:INFO [Chrome 52.0.2743 (Linux 0.0.0)]: Connected on socket /#bNq05S_5S6il-eenAAAA with id 72225563
LOG: 'headers = {"content-type":["application/json"]}'
LOG: 'headers = {"content-type":["application/json"]}'
Global Service : Login Authentication
✔ Should have operator login Authentication
LOG: 'headers = {"content-type":["application/json"],"authorization":["Token ad42hjk234bad8808"]}'
LOG: 'headers = {"content-type":["application/json"],"authorization":["Token ad42hjk234bad8808"]}'
LOG: 'catch 400 = {"_body":"{\"username\":\"xyz#gmail.com\",\"password\":\"761e768a501c30ea8e38\"}","status":400,"ok":false,"statusText":null,"headers":null,"type":null,"url":null}'
LOG: 'catch 400 = {"_body":"{\"username\":\"xyz#gmail.com\",\"password\":\"761e768a501c30ea8e38\"}","status":400,"ok":false,"statusText":null,"headers":null,"type":null,"url":null}'
✔ Should be call error page if login credential wrong
Global Utils : Meta urls API
✔ Should have get Meta urls
LOG: 'page error'
LOG: 'page error'
✔ If get Empty Response of MetaUrls with status code 200
LOG: 'page error'
LOG: 'page error'
✔ If get Empty Response of MetaUrls with status code 400
LOG: 'page error'
LOG: 'page error'
✔ Should not have get Meta urls data with status code 404
Finished in 0.473 secs / 0.431 secs
SUMMARY:
✔ 6 tests completed
karma.conf.js
/**
* #author: #AngularClass
*/
module.exports = function (config) {
var testWebpackConfig = require('./config/webpack.test.js')({env: 'test'});
var configuration = {
// base path that will be used to resolve all patterns (e.g. files, exclude)
basePath: '',
/*
* Frameworks to use
*
* available frameworks: https://npmjs.org/browse/keyword/karma-adapter
*/
frameworks: ['jasmine'],
// list of files to exclude
exclude: [],
/*
* list of files / patterns to load in the browser
*
* we are building the test environment in ./spec-bundle.js
*/
files: [
{ pattern: './config/spec-bundle.js', watched: false }
],
/*
* preprocess matching files before serving them to the browser
* available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
*/
preprocessors: {
'./config/spec-bundle.js': ['coverage', 'webpack', 'sourcemap'],
},
// Webpack Config at ./webpack.test.js
webpack: testWebpackConfig,
coverageReporter: {
type: 'in-memory'
},
remapCoverageReporter: {
'text-summary': null,
json: './coverage/coverage.json',
html: './coverage/html'
},
// Webpack please don't spam the console when running in karma!
webpackMiddleware: {stats: 'errors-only'},
/*
* test results reporter to use
*
* possible values: 'dots', 'progress'
* available reporters: https://npmjs.org/browse/keyword/karma-reporter
*/
reporters: ['mocha', 'coverage', 'remap-coverage'],
// web server port
port: 9876,
// enable / disable colors in the output (reporters and logs)
colors: true,
/*
* level of logging
* possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
*/
logLevel: config.LOG_INFO,
// enable / disable watching file and executing tests whenever any file changes
autoWatch: false,
/*
* start these browsers
* available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
*/
browsers: [
'Chrome'
],
customLaunchers: {
ChromeTravisCi: {
base: 'Chrome',
flags: ['--no-sandbox']
}
},
plugin: [
'karma-coverage',
'karma-mocha-reporter',
'karma-remap-coverage',
'karma-sourcemap-loader',
'istanbul-instrumenter-loader'
],
/*
* Continuous Integration mode
* if true, Karma captures browsers, runs the tests and exits
*/
singleRun: true
};
if (process.env.TRAVIS) {
configuration.browsers = [
'ChromeTravisCi',
'Chrome'
];
}
config.set(configuration);
};
spec-bundle.js
/**
* #author: #AngularClass
*/
/*
* When testing with webpack and ES6, we have to do some extra
* things to get testing to work right. Because we are gonna write tests
* in ES6 too, we have to compile those as well. That's handled in
* karma.conf.js with the karma-webpack plugin. This is the entry
* file for webpack test. Just like webpack will create a bundle.js
* file for our client, when we run test, it will compile and bundle them
* all here! Crazy huh. So we need to do some setup
*/
Error.stackTraceLimit = Infinity;
require('core-js/es6');
require('core-js/es7/reflect');
// Typescript emit helpers polyfill
require('ts-helpers');
require('zone.js/dist/zone');
require('zone.js/dist/long-stack-trace-zone');
require('zone.js/dist/proxy'); // since zone.js 0.6.15
require('zone.js/dist/sync-test');
require('zone.js/dist/jasmine-patch'); // put here since zone.js 0.6.14
require('zone.js/dist/async-test');
require('zone.js/dist/fake-async-test');
// RxJS
require('rxjs/Rx');
var testing = require('#angular/core/testing');
var browser = require('#angular/platform-browser-dynamic/testing');
testing.TestBed.initTestEnvironment(
browser.BrowserDynamicTestingModule,
browser.platformBrowserDynamicTesting()
);
/*
* Ok, this is kinda crazy. We can use the context method on
* require that webpack created in order to tell webpack
* what files we actually want to require or import.
* Below, context will be a function/object with file names as keys.
* Using that regex we are saying look in ../src then find
* any file that ends with spec.ts and get its path. By passing in true
* we say do this recursively
*/
var testContext = require.context('../src', true, /\.spec\.ts/);
/*
* get all the files, for each file, call the context function
* that will require the file and load it up here. Context will
* loop and require those spec files here
*/
function requireAll(requireContext) {
return requireContext.keys().map(requireContext);
}
// requires and returns all modules that match
var modules = requireAll(testContext);
I've had the same problem and it's because the '*.spec.js' files need to be accessible but not included, so you have to do something like this:
files: [
{ pattern: './config/spec-bundle.js', watched: false },
{ pattern: '**/*.spec.js', included: false, served: true, watched: false }
]
This is the source I've found: https://medium.com/#SchizoDuckie/so-your-karma-tests-run-twice-this-is-what-you-need-to-do-be74ce9f257e#.lqrkf24ty

karma + jasmine unit tests show define is not defined

I am using Karma and jasmine to write my unit tests. I transpile ES6 code to ES5 to run the tests on but when ever I run the tests I get an error saying:
Chrome 51.0.2704 (Windows 10 0.0.0) ERROR
Uncaught ReferenceError: define is not defined
My karma.conf.js is this:
// Karma configuration
// Generated on Wed Jun 08 2016 07:12:07 GMT-0400 (Eastern Daylight Time)
module.exports = function (config) {
config.set({
// base path that will be used to resolve all patterns (eg. files, exclude)
basePath: '',
// frameworks to use
// available frameworks: https://npmjs.org/browse/keyword/karma-adapter
frameworks: ['jspm','jasmine'],
// list of files / patterns to load in the browser
files: [
{pattern: 'lib/**/*.min.js', included: false},
{pattern: 'js/Test/Dashboard/Unit/src/*.js', included: true},
{pattern: 'js/Test/Dashboard/Unit/src/**/*.js', included: true},
{pattern: 'js/Test/*Spec.js', included: true},
{pattern: 'js/Test/**/*Spec.js', included: true}
],
// list of files to exclude
exclude: [],
// test results reporter to use
// possible values: 'dots', 'progress'
// available reporters: https://npmjs.org/browse/keyword/karma-reporter
reporters: ['progress'],
// web server port
port: 9876,
// enable / disable colors in the output (reporters and logs)
colors: true,
// level of logging
// possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
logLevel: config.LOG_INFO,
// enable / disable watching file and executing tests whenever any file changes
autoWatch: true,
// start these browsers
// available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
browsers: ['chrome_without_security'],
customLaunchers: {
chrome_without_security: {
base: 'Chrome',
flags: ['--disable-web-security']
}
},
// Continuous Integration mode
// if true, Karma captures browsers, runs the tests and exits
singleRun: false,
// Concurrency level
// how many browser should be started simultaneous
concurrency: Infinity
})
}
The gulp task that runs the ES6-ES6 transpile is this:
gulp.task('build:aurelia', function(){
gulp.src([paths.dashboardPathJs, '!' + paths.dashboardJs])
.pipe(sourcemaps.init())
.pipe(babel({
presets: [ 'es2015-loose', 'stage-1'],
plugins: [
'syntax-flow',
'transform-decorators-legacy',
'transform-flow-strip-types',
'transform-es2015-modules-amd'
]
}))
.pipe(sourcemaps.write('./'))
.pipe(gulp.dest('./js/Test/Dashboard/Unit/src'));
});
I'm completely lost as to why I get the define is not defined error. Thank you in advance.