Karma test runner does not run mocha tests - node.js

When running tests using mocha (./node_modules/.bin/mocha test) the tests in the test file run, and the following is outputted to powershell:
TEST ************
myFunc
- a pending test
0 passing (4ms)
1 pending
When running the same file using karma (./node_modules/.bin/karma start), the console.log("TEST ************"); prints out, but the test suite does not run. Karma gives the following output:
10 05 2020 14:27:24.326:WARN [karma]: No captured browser, open http://localhost:9876/
10 05 2020 14:27:24.352:INFO [karma-server]: Karma v5.0.5 server started at http://0.0.0.0:9876/
10 05 2020 14:27:24.352:INFO [launcher]: Launching browsers ChromeHeadless with concurrency unlimited
10 05 2020 14:27:24.358:INFO [launcher]: Starting browser ChromeHeadless
10 05 2020 14:27:26.898:INFO [Chrome Headless 81.0.4044.138 (Windows 10)]: Connected on socket IBnhFoW1f9d9zLHsAAAA with id 8234878
Chrome Headless 81.0.4044.138 (Windows 10) LOG: 'TEST ************'
Chrome Headless 81.0.4044.138 (Windows 10): Executed 0 of 1 (skipped 1) SUCCESS (0.004 secs / 0 secs)
TOTAL: 0 SUCCESS
test.js
console.log("TEST ************");
describe('myFunc', function() {
it("a pending test");
});
karma.conf.js
module.exports = function(config) {
config.set({
frameworks: ["mocha"],
files: [ "test/test.js"],
plugins: [
"karma-chrome-launcher",
"karma-mocha"
],
browsers: ["ChromeHeadless"]
})
}
package.json
{
"name": "karma-mocha-test",
"devDependencies": {
"karma-chrome-launcher": "^3.1.0",
"karma": "^5.0.5",
"karma-mocha": "^2.0.1",
"mocha": "^7.1.2"
}
}
What am I missing here to make karma run mocha tests and display the results in powershell?

I'm missing a reporter, like so:
,reporters: ["mocha", "coverage-istanbul"]

Related

Importing Node core modules breaks Karma tests (using #open-wc/testing-karma)

macOS Mojave 10.14.5
Node.js v12.6.0
I am trying to set up testing for a vanilla web component, which led me to the #open-wc/testing-karma package. When doing something like this:
src/redblue-video.test.js
import { html, fixture, expect } from '#open-wc/testing';
import RedBlueVideo from './parser-omni.js'; // ES6 web component class
customElements.define( 'redblue-video', RedBlueVideo );
describe( '<redblue-video />', () => {
it( 'embeds YouTube videos', async () => {
const el = await fixture( html`<redblue-video></redblue-video>` );
expect( el ).dom.to.equal( `<redblue-video class="redblue-video" role="application"></redblue-video>` );
} );
} );
…and running it with yarn test (karma start), the test executes fine:
$ yarn test
yarn run v1.17.3
$ karma start
START:
01 08 2019 19:11:03.202:WARN [filelist]: Pattern "/Users/Hugh/Sites/redblue/__snapshots__/**/*.md" does not match any file.
01 08 2019 19:11:03.223:INFO [karma-server]: Karma v4.2.0 server started at http://0.0.0.0:9876/
01 08 2019 19:11:03.223:INFO [launcher]: Launching browsers ChromeHeadlessNoSandbox, ChromeHeadlessNoSandbox with concurrency unlimited
01 08 2019 19:11:03.226:INFO [launcher]: Starting browser ChromeHeadless
01 08 2019 19:11:03.240:INFO [launcher]: Starting browser ChromeHeadless
01 08 2019 19:11:03.893:INFO [HeadlessChrome 75.0.3770 (Mac OS X 10.14.5)]: Connected on socket 4QcOBy0C1_X43S5zAAAA with id 15906039
01 08 2019 19:11:03.922:INFO [HeadlessChrome 75.0.3770 (Mac OS X 10.14.5)]: Connected on socket bcOgxLUp8s7CAZUqAAAB with id 41870378
HeadlessChrome 75.0.3770 (Mac OS X 10.14.5) WARN: 'No Embed URL found'
HeadlessChrome 75.0.3770 (Mac OS X 10.14.5) WARN: 'No Embed URL found'
HeadlessChrome 75.0.3770 (Mac OS X 10.14.5) WARN: 'No nonlinear playlists found'
HeadlessChrome 75.0.3770 (Mac OS X 10.14.5) WARN: 'No nonlinear playlists found'
<redblue-video />
✔ embeds YouTube videos
Finished in 0.025 secs / 0.038 secs # 19:11:07 GMT-0400 (Eastern Daylight Time)
SUMMARY:
✔ 2 tests completed
✨ Done in 5.07s.
But if I try to pull in readFileSync, as in:
import { html, fixture, expect } from '#open-wc/testing';
import { readFileSync } from 'fs';
import RedBlueVideo from './parser-omni.js'; // ES6 web component class
customElements.define( 'redblue-video', RedBlueVideo );
describe( '<redblue-video />', () => {
it( 'embeds YouTube videos', async () => {
const markup = readFileSync( './examples/youtube-embed.hvml' );
const el = await fixture( html`<redblue-video>${markup}</redblue-video>` );
expect( el ).dom.to.equal( `<redblue-video class="redblue-video" role="application">${markup}</redblue-video>` );
} );
} );
…then the test does not run:
$ yarn test
yarn run v1.17.3
$ karma start
START:
01 08 2019 19:16:08.364:WARN [filelist]: Pattern "/Users/Hugh/Sites/redblue/__snapshots__/**/*.md" does not match any file.
01 08 2019 19:16:08.384:INFO [karma-server]: Karma v4.2.0 server started at http://0.0.0.0:9876/
01 08 2019 19:16:08.385:INFO [launcher]: Launching browsers ChromeHeadlessNoSandbox, ChromeHeadlessNoSandbox with concurrency unlimited
01 08 2019 19:16:08.390:INFO [launcher]: Starting browser ChromeHeadless
01 08 2019 19:16:08.397:INFO [launcher]: Starting browser ChromeHeadless
01 08 2019 19:16:09.100:INFO [HeadlessChrome 75.0.3770 (Mac OS X 10.14.5)]: Connected on socket a8fHrCGFmHdZC5qOAAAA with id 88214959
01 08 2019 19:16:09.799:INFO [HeadlessChrome 75.0.3770 (Mac OS X 10.14.5)]: Connected on socket Cq0xMj1wOchVYG13AAAB with id 63311008
HeadlessChrome 75.0.3770 (Mac OS X 10.14.5) ERROR: 'failed to load element http://localhost:9876/base/src/redblue-video.test.js?2133f326ffd8a86c0252453f23aee7a13f7ff7ad'
HeadlessChrome 75.0.3770 (Mac OS X 10.14.5) ERROR: 'failed to load element http://localhost:9876/base/src/redblue-video.test.js?2133f326ffd8a86c0252453f23aee7a13f7ff7ad'
Finished in 0.008 secs / 0 secs # 19:16:11 GMT-0400 (Eastern Daylight Time)
SUMMARY:
✔ 0 tests completed
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
Is it impossible to use Node core modules with Karma tests? Or is there some extra configuration I am missing?
karma.conf.js – This is only different from open-wc’s recommended config via test/**/*.test.js being changed to src/**/*.test.js.
const { createDefaultConfig } = require('#open-wc/testing-karma');
const merge = require('deepmerge');
module.exports = config => {
config.set(
merge(createDefaultConfig(config), {
files: [
// runs all files ending with .test in the test folder,
// can be overwritten by passing a --grep flag. examples:
//
// npm run test -- --grep test/foo/bar.test.js
// npm run test -- --grep test/bar/*
{ pattern: config.grep ? config.grep : 'src/**/*.test.js', type: 'module' }
],
// see the karma-esm docs for all options
esm: {
// if you are using 'bare module imports' you will need this option
nodeResolve: true
}
})
);
return config;
};
package.json:
"scripts": {
"test": "karma start",
"test:coverage": "karma start --coverage",
"test:watch": "karma start --auto-watch=true --single-run=false",
"test:update-snapshots": "karma start --update-snapshots",
"test:prune-snapshots": "karma start --prune-snapshots",
"test:compatibility": "karma start --compatibility all --auto-watch=true --single-run=false"
},
"devDependencies": {
"#open-wc/chai-dom-equals": "^0.12.36",
"#open-wc/testing": "^2.2.2",
"#open-wc/testing-karma": "^3.1.6",
"codecov": "^3.5.0",
"eslint": "^6.1.0",
"eslint-config-airbnb-base": "^13.2.0",
"eslint-config-hughx": "^0.0.2",
"eslint-plugin-import": "^2.18.2",
"lit-html": "^1.1.1",
"webpack": "^4.38.0"
}
You cannot use core node modules in your karma tests unless you do something tricky. Karma tests run in the browser (even though the karma server runs on node). The tests therefore have no access to node core modules.
The only way to include node modules in your karma scripts is to use something like browserify or webpack.
But, more importantly, since the tests are running in the browser, you cannot access the file system directly. Your approach of trying to read a file on the disk will not work. You will need to be able to serve the file from your karma server using a fetch request or something similar.
You can specify where the karma server looks for resources using the basePath option in the configuration file.

Firebase - Issue during deployment getting error : Error: An unexpected error has occurred

When i test my application using the below command in the localhost, it works fine.
firebase serve --only functions,hosting
But when i tried to deploy it using below command. It fails with error message (Error: An unexpected error has occurred.). Does not give much details
firebase deploy
or
firebase deploy --only functions,hosting
Initial error was to update firebase-functions and firebase-admin so i went ahead and updated it after reading the guide in below link. Iam not using any of those features.
https://firebase.google.com/docs/functions/beta-v1-diff#realtime-database
npm install firebase-functions#latest --save
npm install firebase-admin#5.11.0 --save
npm install -g firebase-tools
Here is the output using command : firebase deploy --debug
[debug] [2018-05-14T18:59:35.734Z] ----------------------------------------------------------------------
[debug] [2018-05-14T18:59:35.739Z] Command: C:\Program Files\nodejs\node.exe C:\Users\Sushanth\AppData\Roaming\npm\node_modules\firebase-tools\bin\firebase deploy --only functions,hosting
[debug] [2018-05-14T18:59:35.740Z] CLI Version: 3.18.4
[debug] [2018-05-14T18:59:35.740Z] Platform: win32
[debug] [2018-05-14T18:59:35.740Z] Node Version: v8.10.0
[debug] [2018-05-14T18:59:35.741Z] Time: Tue May 15 2018 00:29:35 GMT+0530 (India Standard Time)
[debug] [2018-05-14T18:59:35.741Z] ----------------------------------------------------------------------
[debug]
[debug] [2018-05-14T18:59:35.759Z] > command requires scopes: ["email","openid","https://www.googleapis.com/auth/cloudplatformprojects.readonly","https://www.googleapis.com/auth/firebase","https://www.googleapis.com/auth/cloud-platform"]
[debug] [2018-05-14T18:59:35.762Z] > authorizing via signed-in user
[debug] [2018-05-14T18:59:35.765Z] > refreshing access token with scopes: ["email","https://www.googleapis.com/auth/cloud-platform","https://www.googleapis.com/auth/cloudplatformprojects.readonly","https://www.googleapis.com/auth/firebase","openid"]
[debug] [2018-05-14T18:59:35.766Z] >>> HTTP REQUEST POST https://www.googleapis.com/oauth2/v3/token
{ refresh_token: '1/V2t23LrBy9dznRfmTQnnh-0x3k3RrWFiA2EbNwRErOU',
client_id: '563584335869-fgrhgmd47bqnekij5i8b5pr03ho849e6.apps.googleusercontent.com',
client_secret: 'j9iVZfS8kkCEFUPaAeJV0sAi',
grant_type: 'refresh_token',
scope: 'email https://www.googleapis.com/auth/cloud-platform https://www.googleapis.com/auth/cloudplatformprojects.readonly https://www.googleapis.com/auth/firebase openid' }
Tue May 15 2018 00:29:35 GMT+0530 (India Standard Time)
[debug] [2018-05-14T18:59:36.385Z] <<< HTTP RESPONSE 200
[debug] [2018-05-14T18:59:36.393Z] >>> HTTP REQUEST GET https://admin.firebase.com/v1/projects/stashit-7885bob
Tue May 15 2018 00:29:36 GMT+0530 (India Standard Time)
[debug] [2018-05-14T18:59:37.606Z] <<< HTTP RESPONSE 200
[debug] [2018-05-14T18:59:37.607Z] >>> HTTP REQUEST GET https://admin.firebase.com/v1/database/stashit-7885bob/tokens
Tue May 15 2018 00:29:37 GMT+0530 (India Standard Time)
[debug] [2018-05-14T18:59:38.662Z] <<< HTTP RESPONSE 200
[info]
[info] === Deploying to 'stashit-7885bob'...
[info]
[info] i deploying functions, hosting
[debug] [2018-05-14T18:59:46.087Z] > [functions] package.json contents: {
"name": "functions",
"description": "Cloud Functions for Firebase",
"scripts": {
"serve": "firebase serve --only functions",
"shell": "firebase experimental:functions:shell",
"start": "npm run shell",
"deploy": "firebase deploy --only functions",
"logs": "firebase functions:log"
},
"dependencies": {
"body-parser": "^1.18.2",
"cookie-parser": "^1.4.3",
"cors": "^2.8.4",
"ejs": "^2.5.9",
"express": "^4.16.3",
"firebase": "^5.0.2",
"firebase-admin": "^5.11.0",
"firebase-functions": "^1.0.2"
},
"private": true
}
[info] i functions: ensuring necessary APIs are enabled...
[debug] [2018-05-14T18:59:46.087Z] >>> HTTP REQUEST GET https://servicemanagement.googleapis.com/v1/services/cloudfunctions.googleapis.com/projectSettings/stashit-7885bob?view=CONSUMER_VIEW
Tue May 15 2018 00:29:46 GMT+0530 (India Standard Time)
[debug] [2018-05-14T18:59:46.092Z] >>> HTTP REQUEST GET https://servicemanagement.googleapis.com/v1/services/runtimeconfig.googleapis.com/projectSettings/stashit-7885bob?view=CONSUMER_VIEW
Tue May 15 2018 00:29:46 GMT+0530 (India Standard Time)
[debug] [2018-05-14T18:59:48.558Z] <<< HTTP RESPONSE 200
[debug] [2018-05-14T18:59:48.586Z] <<< HTTP RESPONSE 200
[info] + functions: all necessary APIs are enabled
[debug] [2018-05-14T18:59:48.588Z] >>> HTTP REQUEST GET https://cloudresourcemanager.googleapis.com/v1/projects/stashit-7885bob
Tue May 15 2018 00:29:48 GMT+0530 (India Standard Time)
[debug] [2018-05-14T18:59:50.672Z] <<< HTTP RESPONSE 200
[debug] [2018-05-14T18:59:50.673Z] >>> HTTP REQUEST GET https://mobilesdk-pa.googleapis.com/v1/projects/288692255744:getServerAppConfig
Tue May 15 2018 00:29:50 GMT+0530 (India Standard Time)
[debug] [2018-05-14T18:59:51.783Z] <<< HTTP RESPONSE 200
[debug] [2018-05-14T18:59:52.294Z] TypeError: Path must be a string. Received [ 'public/',
'public/css',
'public/js',
'public/mdb-css',
'public/mdb-js',
'functions/js',
'public/images' ]
at assertPath (path.js:28:11)
at Object.resolve (path.js:211:7)
at module.exports (C:\Users\Sushanth\AppData\Roaming\npm\node_modules\firebase-tools\lib\resolveProjectPath.js:7:15)
at module.exports (C:\Users\Sushanth\AppData\Roaming\npm\node_modules\firebase-tools\lib\deploy\hosting\prepare.js:31:39)
at _chain (C:\Users\Sushanth\AppData\Roaming\npm\node_modules\firebase-tools\lib\deploy\index.js:26:38)
at C:\Users\Sushanth\AppData\Roaming\npm\node_modules\firebase-tools\lib\deploy\index.js:29:14
at <anonymous>
at process._tickDomainCallback (internal/process/next_tick.js:228:7)
[error]
[error] Error: An unexpected error has occurred.
And my firebase.json file looks like this
{
"hosting": {
"public": ["public/", "public/css", "public/js", "public/mdb-css", "public/mdb-js", "functions/js", "public/images"],
"rewrites":[
{"source" : "/timestamp", "function" : "app"},
{"source" : "/stashlogin", "function" : "app"},
{"source" : "/stash", "function" : "app"},
{"source" : "/get", "function" : "app"},
{"source" : "/put", "function" : "app"},
{"source" : "/categorycolor", "function" : "app"},
{"source" : "/category", "function" : "app"},
{"source" : "/category/**", "function" : "app"},
{"source" : "/put/**", "function" : "app"},
{"source" : "/delete/**", "function" : "app"},
{"source" : "/profile", "function" : "app"},
{"source" : "/feedback", "function" : "app"}
],
"ignore": [
"firebase.json",
"**/.*",
"**/node_modules/**"
]
}
}
Please let me know how to proceed as there is not reason for the error message. I am actually stuck.
Your public directory must be a single string, not an array.

Grunt executes multiple times, creates infinite loop

We are working as on a project with a couple of other devs on GIT, using the same repo, it works fine with everyone else. However, when I run grunt it executes multiple times, seems to be running into an infinite loop, without me actually making any changes. It's only happening to me on a different computer
I am considering that maybe I need something else installed.
I deleted node, npm and reinstalled with homebrew which I'm also using for updates. Node v5.3.0, npm 3.3.12
Running Mavericks.
What am I missing?
Here's the loop:
Reloading watch config...
Running "watch" task
Waiting...
>> File "Gruntfile.js" changed.
>> File "js/all-js/bootstrap-hover-dropdown.min.js" changed.
>> File "js/all-js/site.js" changed.
Running "uglify:build" (uglify) task
>> 1 file created.
Done, without errors.
Completed in 3.740s at Tue Jan 05 2016 13:11:07 GMT-0500 (ECT) - Waiting...
[BS] File changed: js/site.min.js
Reloading watch config...
Running "watch" task
Waiting...
>> File "js/all-js/bootstrap.js" changed.
>> File "Gruntfile.js" changed.
Running "uglify:build" (uglify) task
>> 1 file created.
Done, without errors.
Completed in 1.869s at Tue Jan 05 2016 13:11:10 GMT-0500 (ECT) - Waiting...
[BS] File changed: js/site.min.js
>> File "js/all-js/bootstrap-hover-dropdown.min.js" changed.
Running "uglify:build" (uglify) task
>> 1 file created.
Done, without errors.
Completed in 1.885s at Tue Jan 05 2016 13:12:04 GMT-0500 (ECT) - Waiting...
[BS] File changed: js/site.min.js
Reloading watch config...
Running "watch" task
Waiting...
>> File "Gruntfile.js" changed.
Here's my Gruntfile.js:
module.exports = function(grunt) {
//Get all tasks from the package.json file
require("matchdep").filterDev("grunt-*").forEach(grunt.loadNpmTasks);
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
/* Concurrent Task */
concurrent: {
watch: {
tasks: ['watch', 'compass:dist', 'browserSync'],
options: {
logConcurrentOutput: true
}
}
},
/* SASS task */
compass: {
dist: {
options: {
sassDir: ['SASS/'],
cssDir: ['css/'],
environment: 'development', /* development | production */
importPath: ['SASS/'],
outputStyle: 'compressed', /* expanded for development | compressed for production */
watch: true,
sourcemap: true
},
},
live: {
options: {
sassDir: ['SASS/'],
cssDir: ['css/'],
environment: 'production', /* development | production */
importPath: ['SASS/'],
outputStyle: 'compressed', /* expanded for development | compressed for production */
watch: false,
force: true,
},
},
},
/* Javascript Tasks */
uglify: {
// Uglify files
build: {
src: [
'js/all-js/bootstrap.js',
'js/all-js/site.js'
],
dest: 'js/site.min.js'
}
},
/* Run tasks when needed */
watch: {
js: {
files: ['js/all-js/*.js'],
tasks: ['uglify'],
options: { livereload: true }
},
gruntfile: {
files: ['Gruntfile.js'],
options: {reload: true}
}
},
/* Browser Reload with BrowserSync */
browserSync: {
bsFiles: {
src : [
'css/**/*.css',
'js/site.min.js',
'**/*.php'
]
},
}
});
// Where we tell Grunt what to do when we type "grunt" into the terminal.
grunt.registerTask('default', ['concurrent:watch']);
grunt.registerTask('live', ['compass:live']);
};
Here's my package.json file:
{
"name": "ourframework",
"version": "0.1.0",
"devDependencies": {
"grunt": "~0.4.1",
"grunt-contrib-compass": "*",
"grunt-browser-sync": "*",
"grunt-contrib-watch": "*",
"grunt-concurrent": "*",
"grunt-contrib-uglify": "*",
"matchdep": "*"
}
}
Look at the timestamps in the grunt output, eg:
Completed in 3.740s at Tue Jan 05 2016 13:11:10
Completed in 1.885s at Tue Jan 05 2016 13:12:04
Notice these compilations are a minute apart - you are running the grunt watch task. This will watch a set of specified files and re-run tasks if there are any changes.
There is no 'loop' - it will simply re-compile every time something changes, which is often desirable.
You can see your default task is set to concurrent:watch
grunt.registerTask('default', ['concurrent:watch']);
So if you just type grunt, it will run that task.

Karma/Jasmine tests fail with error: 'Uncaught Error: Module name "simple_test.js" has not been loaded yet for context: _. Use require([])'

I am using Karma and Jasmine to run tests on my project built with React. When I try to run my Karma tests I get this error in the console:
Running "karma:test" (karma) task
WARN `start` method is deprecated since 0.13. It will be removed in 0.14. Please use
server = new Server(config, [done])
server.start()
instead.
07 09 2015 14:46:56.552:WARN [plugin]: Error during loading "karma-opera-launcher" plugin:
ENOENT, no such file or directory './config/prefs.ini'
Hash: 8344a6c0a9b3c44a5636
Version: webpack 1.12.1
Time: 6ms
webpack: bundle is now VALID.
07 09 2015 14:46:56.685:INFO [karma]: Karma v0.13.9 server started at http://localhost:9876/
07 09 2015 14:46:56.689:INFO [launcher]: Starting browser Chrome
07 09 2015 14:46:56.700:INFO [launcher]: Starting browser Firefox
07 09 2015 14:46:56.713:INFO [launcher]: Starting browser PhantomJS
07 09 2015 14:46:57.063:INFO [PhantomJS 1.9.8 (Linux 0.0.0)]: Connected on socket X4i_xm1JTKdTSJO2AAAA with id 74978391
PhantomJS 1.9.8 (Linux 0.0.0) ERROR
Error: Module name "simple_test.js" has not been loaded yet for context: _. Use require([])
http://requirejs.org/docs/errors.html#notloaded
at /home/michael/repository/short-stories/node_modules/requirejs/require.js:140
07 09 2015 14:46:58.890:INFO [Chromium 44.0.2403 (Ubuntu 0.0.0)]: Connected on socket K4FoGDjsszglqxvVAAAB with id 26278080
Chromium 44.0.2403 (Ubuntu 0.0.0) ERROR
Uncaught Error: Module name "simple_test.js" has not been loaded yet for context: _. Use require([])
http://requirejs.org/docs/errors.html#notloaded
at /home/michael/repository/short-stories/node_modules/requirejs/require.js:140
07 09 2015 14:47:02.441:INFO [Firefox 40.0.0 (Ubuntu 0.0.0)]: Connected on socket EJQMu5bHS1DnJLRXAAAC with id 52731426
Firefox 40.0.0 (Ubuntu 0.0.0) ERROR
Error: Module name "simple_test.js" has not been loaded yet for context: _. Use require([])
http://requirejs.org/docs/errors.html#notloaded
at /home/michael/repository/short-stories/node_modules/requirejs/require.js:165
Warning: Task "karma:test" failed. Use --force to continue.
I have tried the recommendations at http://requirejs.org/docs/errors.html#notloaded, but it didn't change the error. I also tried making my require statements into one big callback hell, but it didn't fix the issue. I'm sure the problem is that it's trying to run the tests before loading the modules, but if I can't make it wait by using callbacks, I'm not sure how to deal with the issue. Any help would be greatly appreciated, Thanks in advance.
I'll paste my karma.conf.js, story_test.js, and test_entry.js files below. Let me know if there is more info that will help. You can view the full project on my GitHub Repo.
Here's my karam.conf.js:
// Karma configuration
// Generated on Thu Jul 02 2015 15:56:34 GMT-0700 (PDT)
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', 'requirejs'],
// list of files / patterns to load in the browser
files: [
__dirname + '/node_modules/phantomjs-polyfill/bind-polyfill.js',
__dirname + '/node_modules/requirejs/require.js',
__dirname + '/node_modules/karma-requirejs/lib/adapter.js',
__dirname + '/test/karma_tests/*entry.js'
],
//plugins to start browsers
plugins : [
'karma-junit-reporter',
'karma-phantomjs-launcher',
'karma-chrome-launcher',
'karma-firefox-launcher',
'karma-opera-launcher',
'karma-ie-launcher',
'karma-jasmine',
'karma-chai',
'karma-webpack',
'karma-requirejs',
'karma-script-launcher'
],
// list of files to exclude
exclude: [
],
// preprocess matching files before serving them to the browser
// available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
preprocessors: {
'test/karma_tests/*test.js': ['webpack'],
// 'test/**/*_test.js': ['webpack']
},
webpack: {
// karma watches the test entry points
// (you don't need to specify the entry option)
// webpack watches dependencies
// webpack configuration
module: {
loaders: [{
test: /\.jsx$/,
loader:'jsx-loader'
}]
}
},
// 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: false,
// start these browsers
// available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
browsers: ['Chrome', 'Firefox', 'PhantomJS'],
// Continuous Integration mode
// if true, Karma captures browsers, runs the tests and exits
singleRun: true,
// Set timeout to 100 seconds
// browserNoActivityTimeout: 100000
});
};
Here's my story_test.js:
'use strict';
var React = require('react/addons');
var Story = require('../../app/js/components/story.jsx');
var TestUtils = React.addons.TestUtils;
var testUtilsAdditions = require('react-testutils-additions');
describe('Story component', function () {
var component;
beforeEach(function () {
var element = React.createElement(Story);
element.props.data = {
storyTitle: 'front end test title',
author : 'front end author',
storyText : 'front end story text'
};
component = TestUtils.renderIntoDocument(element);
});
it('should display a story', function () {
expect(component.props.data).toBeDefined();
expect(component.props.data.storyTitle).toBeDefined();
expect(component.props.data.storyTitle).toBe('front end test title');
expect(component.props.data.author).toBe('front end author');
expect(component.props.data.storyText).toBe('front end story text');
});
});
And finally here's the test_entry.js:
'use strict';
require('./simple_test.js');
require('./story_test.js');
The error seems to come from the http://requirejs.org project and I think is trying to get you to change from using synchronous CommonJS require calls such as;
require('./simple_test.js');
require('./story_test.js');
to asynchronous AMD calls such as;
require(['./simple_test.js', './story_test.js'], function() {
// simple_test and story_test are now loaded
});
It's not clear to me from what you've posted which modules are requirejs/AMD and which aren't, it looks like you may possibly have a confusing mixture of the two? Sorry I can't help much more than this.

Grunt-mocha-test Xunit reporter writes the whole console output to the xunit file

I'm using grunt-mocha-test for running our mocha tests. I want to be able to run the tests and generate the xunit report and get the coverage (with blanket.js). I have the following sections in my gruntfile:
mochaTest: {
'unit-jenkins': {
options: {
reporter: 'XUnit',
require: paths.test + '/blanket',
captureFile: paths.tmp + '/xunit.xml'
},
src: [paths.test + '/unit/**/*.js'],
},
'integration-jenkins': {
options: {
reporter: 'XUnit',
require: paths.test + '/blanket',
captureFile: paths.tmp + '/xunit.xml'
},
src: [paths.test + '/integration/**/*.js']
},
coverage: {
options: {
reporter: 'html-cov',
quiet: true,
captureFile: paths.tmp + '/coverage.html'
},
src: [paths.test + '/**/*.js']
}
},
and
grunt.registerTask('test-jenkins', [
'mochaTest:unit-jenkins', // run unit tests
'mochaTest:integration-jenkins', // run unit tests
]);
when I run grunt test-jenkins I can see the test output and the xunit output on the console. Moreover, the xunit file is created, however, it consists of both the tests output and the xunit output, e.g.:
[14:30:17.164Z] TRACE App: HTTP Response /versions
HTTP/1.1 200 OK
HTTP/1.1 200 OK
X-Powered-By: Express
Content-Type: application/json; charset=utf-8
Content-Length: 46
ETag: "-1409762768"
Date: Mon, 17 Feb 2014 14:30:17 GMT
Connection: close
<testsuite name="Mocha Tests" tests="1" failures="0" errors="0" skipped="0" timestamp="Mon, 17 Feb 2014 14:30:17 GMT" time="0.029">
<testcase classname="Application" name="should contain description of API versions" time="0.028"/>
</testsuite>
How should grunt-mocha-test be configured so that the xunit output file consists solely of the xunit output?
I had the same problem with Selenium. I got around it with the following task:
var outputFile = process.env.MOCHA_OUTPUT_FILE || 'xunit_results.xml';
grunt.registerTask('cleanXunitFile', 'Remove Selenium/WebDriver output from xunit file', function() {
if (grunt.file.exists('./' + outputFile)) {
var file = grunt.file.read('./' + outputFile);
if (file.indexOf("<testsuite")) {
grunt.file.write('./' + outputFile, file.substring(file.indexOf("<testsuite")));
}
}
else {
grunt.log.error("'cleanXunitFile' task was specified but file " + outputFile + " does not exist.");
}
});
I can see the test output and the xunit output on the console. Moreover, the xunit file is created, however, it consists of both the tests output and the xunit output
I am afraid this is a know bug of mocha.
There is a pending pull request trying to address these issues, see
https://github.com/visionmedia/mocha/pull/1218

Resources