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

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

Related

Unable to run specific spec file using protractor

I am trying to organize the "test files" into folders and run a specific spec file using protractor . For that i created below files.
heroes_spec.js file contains below code
var HeroesHomePage = require('C:\Users\agudla\Desktop\VSCodeWorkSpace\my-app\e2e\Heroes\heros_po.js');
describe('Heroes page tests' , function(){
var heroespage = new HeroesHomePage();
heroespage.heroesLinkClickEvent();
browser.driver.sleep(3000);
});
hero_po.js file contains below code
var heroesLinkClickEvent;
var hero_page = function() {
this.heroesLinkClickEvent= function(){
element(by.linkText('Heroes')).click();
}
};
hero_po.js is as below
module.exports = hero_page;
My protractor.conf.js file code is below
exports.config = {
allScriptsTimeout: 11000,
suites: {
heroespage : 'C:\Users\agudla\Desktop\VSCodeWorkSpace\my-app\e2e\Heroes\heroes_spec.js'
},
capabilities:
{
'browserName': 'chrome',
'seleniumAddress':'http://localhost:4444/wd/hub'
},
baseUrl: 'http://localhost:4200/',
framework: 'jasmine',
jasmineNodeOpts: {
showColors: true,
defaultTimeoutInterval: 30000,
includeStackTrace: true
},
onPrepare() {
require('ts-node').register({
project: 'e2e/tsconfig.e2e.json'
});
},
}
When i run protractor protractor.conf.js --suite heroespage command after starting "selenium server".
No specs found message is displaying.
Can any one help me to solve this issue.
Are you aware, that Javascript uses forward-slashes / for paths and not backslashes \?
With a backslash you basically just exit the next character.
So try either with / instead of \
heroespage : 'C:/Users/agudla/Desktop/VSCodeWorkSpace/my-app/e2e/Heroes/heroes_spec.js'
Do this in all your paths within Protractor.
That should do the trick.
Give relative path to your project root folder.
suites: {
heroespage: ['e2e\Heroes\heroes_spec.js']
}
This is the command passed:
protractor src/test/javascript/protractor.conf.js --specs src/test/javascript/e2e/entities\points\points.spec.t
s
which is protractor conf files and then command line parameters followed by value.

Node JS + Grunt-sonar-runner + Code Coverage not showing

I created a REST service in node js and wrote the test cases using mocha. I have been able to generate the code coverage using istanbul and is working absolutely fine. Now my requirement is to show the code coverage using Sonar. The code compliance violations are getting listed as expected. But the code coverage is not getting generated in sonar. I doubt there is something wrong with the gruntfile.js configuration. Currently, I generate the code compliance violation by copying the source inside the grunt-sonar-runner folder within node_modules and execute grunt-sonar-runner. My current folder structure is as shown below :
<ProjectRoot>
|--server.js
|--[test]
|--|--serverTest.js
|--[node_modules]
|--|--[grunt-sonar-runner]
|--|--|--[src]
|--|--|--|--server.js
In the gruntfile.js,
grunt.initConfig({
jshint: {
all: [
'Gruntfile.js',
'tasks/*.js',
'test/*.js'
],
options: {
jshintrc: '.jshintrc'
}
},
// Before generating any new files, remove any previously-created files.
clean: {
tests: ['tmp']
},
// Configuration to be run (and then tested).
sonarRunner: {
analysis: {
options: {
debug: true,
separator: '\n',
sonar: {
host: {
url: 'http://localhost:9000'
},
jdbc: {
url: 'jdbc:h2:tcp://localhost:9092/sonar',
username: 'sonar',
password: 'sonar'
},
projectKey: 'sonar:grunt-sonar-runner:0.1.0',
projectName: 'Grunt Sonar Runner',
projectVersion: '0.10',
sources: ['src'].join(','),
language: 'js',
sourceEncoding: 'UTF-8'
}
}
},
dryRun: {
options: {
dryRun: true,
debug: true,
separator: '\n',
sonar: {
host: {
url: 'http://localhost:9000'
},
jdbc: {
url: 'jdbc:mysql://localhost:3306/sonar',
username: 'sonar',
password: 'sonar'
},
projectKey: 'sonar:grunt-sonar-runner:0.1.0',
projectName: 'Grunt Sonar Runner',
projectVersion: '0.10',
sources: ['src'].join(','),
exclusions: '**/R.js'
}
}
}
},
// Unit tests.
mochaTest: {
test: {
options: {
reporter: 'spec'
},
src: ['test/**/*.js'],
}
}
});
we have two sections --> analysis and dryRun. What is this dryRun ?
Just outside that, we have a key called mochaTest.
While running mocha with istanbul, I am getting coverage reports generated in the project root inside a folder called coverage. Unfortunately it is not getting listed in sonar. Any help would be appreciated.
Thanks in Advance,
Noble
Just had to define a sonar-roject.properties in the project root folder. Inside that properties file, we can specify the relative path to the lcov.info generated by istanbul. After starting up the sonar qube server, just run sonar-runner (provided sonar runner is present in the system path). Sonar reports will be visible in sonar dashboard

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.

How to create api documents with grunt-ngdocs

I'm trying to create API documents through grunt-ngdocs.
The partials are created but the index.html doesn't have the correct links to it.
I have in my gruntfile.js:
module.exports = function (grunt) {
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
karma: {
unit: {
configFile: 'karma.conf.js'
}
},
uglify: {
options: {
// the banner is inserted at the top of the output
banner: '/*! <%= pkg.name %> <%= grunt.template.today("dd-mm-yyyy") %> */\n'
},
dist: {
files: {
'web/js/app.min.js': ['web/js/app.js']
}
}
},
ngdocs: {
options: {
dest: 'docs',
scripts: ['web/js/app.js'],
title: 'My Documentation'
},
api: {
src: ['web/**/*.js'],
title: 'API Documentation'
}
},
clean:['docs','testResult']
});
grunt.loadNpmTasks('grunt-karma');
grunt.loadNpmTasks('grunt-ngdocs');
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.loadNpmTasks('grunt-contrib-clean');
grunt.registerTask('default', ['clean','uglify', 'ngdocs', 'karma']);
};
and my js file like this
/**
* #ngdoc overview
* #ngdoc directive
* #name myApp.maincontroller:controller
* #description
*
* # myApp
* The factoryName is my favorite service in the world.
*
*/
var myApp = angular.module('myApp',[]);
myApp.controller("MainController", function($scope) {
$scope.model = {
myValue: "Run you fools!"
};
});
/**
* #ngdoc function
* #name mySuperFunction
* #returns {int} The int representing a Firebase resource
*/
function mySuperFunction() {
var i = 5;
var j = 5;
i += j;
return i;
}
but when I run
grunt
in the command line, the result is this
C:\Users\Lino Simões\Documents\bitbucket\test>grunt -d --force
Running "clean:0" (clean) task
[D] Task source: C:\Users\Lino Simões\Documents\bitbucket\test\node_modules\grun
t-contrib-clean\tasks\clean.js
Cleaning docs...OK
Running "clean:1" (clean) task
[D] Task source: C:\Users\Lino Simões\Documents\bitbucket\test\node_modules\grun
t-contrib-clean\tasks\clean.js
Cleaning testResult...OK
Running "uglify:dist" (uglify) task
[D] Task source: C:\Users\Lino Simões\Documents\bitbucket\test\node_modules\grun
t-contrib-uglify\tasks\uglify.js
File web/js/app.min.js created: 796 B → 210 B
Running "ngdocs:api" (ngdocs) task
[D] Task source: C:\Users\Lino Simões\Documents\bitbucket\test\node_modules\grun
t-ngdocs\tasks\grunt-ngdocs.js
Generating Documentation...
DONE. Generated 2 pages in 256ms.
Running "karma:unit" (karma) task
[D] Task source: C:\Users\Lino Simões\Documents\bitbucket\test\node_modules\grun
t-karma\tasks\grunt-karma.js
INFO [karma]: Karma v0.12.17 server started at http://localhost:9876/
INFO [launcher]: Starting browser PhantomJS
INFO [PhantomJS 1.9.7 (Windows 7)]: Connected on socket dFX-dKGVINA6PBjB5Gu9 wit
h id 91061839
PhantomJS 1.9.7 (Windows 7): Executed 8 of 8 SUCCESS (0.008 secs / 0.004 secs)
Done, without errors.
so, this generates 2 files, but when I go to the index.html under docs I have this:
but in my docs/partials/api/ I have the partials created by the ngdocs.
my project tree is like this:
Did you have angular.js and angular-animate.js in your web/js/app.js? Check it. And add to "options" html5Mode: false
for ng1.6 works for me:
ngdocs: {
all: ['app/**/*.js']
}
you will see the old version of angular 1.2.* in
cat docs/js/angular.min.js | grep v1
AngularJS v1.2.16
but it does not affect your source files.
also, dont forget run server
for generated folder docs:
e.g using python
pushd ./dist; python -m SimpleHTTPServer 9000; popd #v 2.*
pushd ./dist; python -m http.server 9000; popd #v 3.*
unfortunately, adding angular.js and angular-animate.js to scripts option doesn't work for me

Generating istanbul code coverage reports for jasmine tests run (via grunt) on a browserify bundle in phantomjs

The title says it all really. Despite trawling the internet I haven't found a single example of a solution to this problem.
Here are some near misses
https://github.com/amitayd/grunt-browserify-jasmine-node-example - grunt, browserify and jasmine
https://github.com/gotwarlost/istanbul/issues/59#issuecomment-18799734 - browserify and istanbul
Here is my in-progress code https://github.com/wheresrhys/on-guard/tree/browserify (note it's the 'browserify' branch - Gruntfile.js is a bit of a mess but will tidy it up shortly). My initial investigations using console.log indicate that somehow bundle.src.js is being loaded in the page but when the tests are run (and passed!) the code in bundle.src.js isn't being run, so I have a feeling it might be an aliasing problem... though one that's limited to phantomjs as when I open the specrunner in chrome the code is getting run.
I'm using grunt-browserify + browserify-istanbul + grunt-contrib-jasmine + grunt-template-jasmine-istanbul as solution. This solution has also excluded third party libraries when building source files using browserify.
Show the code first, I'll explain later,
grunt.initConfig({
browserify: {
// build specs using browserify
specs: {
src: ["spec/**/*Spec.js"],
dest: "spec/build/specs.js",
options: {
debug: true
}
},
// build source files using browserify and browserify-istanbul
dev: {
options: {
debug: true,
browserifyOptions: {
standalone: 'abc'
},
transform: [['browserify-istanbul', {
ignore: ['**/node_modules/**'], // ignore third party libs
defaultIgnore: true
}]]
},
src: ['abc.js'],
dest: 'dist/abc.js'
}
},
connect: {
server: {
options: {
port: 7000
}
}
},
// test using jasmine, generate coverage report using istanbul
jasmine: {
coverage: {
src: ['dist/abc.js'],
options: {
junit: {
path: 'bin/junit'
},
host: 'http://localhost:7000/',
specs: 'spec/build/specs.js',
keepRunner: true,
summary: true,
template: require('grunt-template-jasmine-istanbul'),
templateOptions: {
replace: false, // *** this option is very important
coverage: 'bin/coverage/coverage.json',
report: [
{
type: 'html',
options: {
dir: 'spec/coverage/html'
}
}]
}
}
}
}
grunt.registerTask('specs', ['browserify:specs', 'browserify:dev', 'connect', 'jasmine']);
The steps of generating istanbul coverage report can be concluded into three:
Instrument code
Run test
Generate coverage report
In our solution, we use browerify-istanbul in step 1, grunt-contrib-jasmine and runt-template-jasmine-istanbul in step 2 and 3.
browserify-istanbul will let you instrument code in browserify building step, in this way, we can easily ignore third party libs. But the grunt-template-jasmine-istanbul will instrument code again. To avoid this, you can set replace to false in the options.
Refs:
Istanbul steps
broswerify-istanbul
grunt-contrib-jasmine
grunt-template-jasmine-istanbul -- replace option

Resources