I have following hello World test to my __tests__ folder:
hello-test.js:
describe('hello world', function() {
it('basic test', function() {
expect(1).toBe(1);
});
});
My aim is to eventually write tests in es6 and run using a gulp task. I have tried running the above with the following gulp task:
gulp.task('jest', ['test-compile'], function(done){
jest.runCLI({
rootDir : __dirname,
//scriptPreprocessor : "../node_modules/babel-jest",
testFileExtensions : ["es6", "js"],
}, __dirname, function (result) {
if (result) {
console.log(result);
} else {
console.log('Tests Failed');
}
done();
});
});
I have also tried running jest using the globally install jest-cli and cannot get it to work, I also tried using the npm test way as shown on line but no matter which of these I try I just get Using Jest CLI v0.6.0 in the terminal, no errors no results.
I am very confused as I seem to be doing what all the doc's online say. I am using Node 4.2.1 if that has any bearing
Related
My use case is pretty simple:
First I want to run node server.js(start my Node.js app) - and after Node has started - I want to run mocha test (running some tests on the API provided by previous server.js) by executing npm run test.
The script: "test": "NODE_ENV=development node server.js && mocha test"
Node starts, but unfortunately the mocha testdoes not seem to be executed:
So how can I execute mocha test after node server.js?
The reason why you're running into this is because node server.js continuously runs until killed (Ctrl + C) or a fatal unhandled exception occurs. Since the node process keeps running mocha test never get executed.
One approach to this would be to use gulp as a task runner and utilize tasks implementing gulp-nodemon and gulp-mocha. If you've never used Gulp before or are unfamiliar with task runners I suggest you read the docs beforehand just to get an idea of how it works.
Add the gulpfile.js below to your app (adjust some of the settings as necessary) and modify your package.json scripts with the test script below and this should solve your issue.
gulpfile.js
var gulp = require('gulp');
var mocha = require('gulp-mocha');
var nodemon = require('gulp-nodemon');
gulp.task('nodemon', (cb) => {
let started = false;
return nodemon({
script: 'server.js'
})
.on('start', () => {
if (!started) {
started = true;
return cb();
}
})
.on('restart', () => {
console.log('restarting');
});
});
gulp.task('test', ['nodemon'], function() {
return gulp.src('./test/*.js')
.pipe(mocha({reporter: 'spec' }))
once('error', function() {
process.exit(1);
})
.once('end', function() {
process.exit();
});
});
package.json scripts
{
"scripts": {
"test": "NODE_ENV=development gulp test"
}
}
Supertest Alternative
A more elegant solution ,and in my opinion the better option, would be to rewrite your tests to use supertest. Basically what you do with supertest is pass your Express instance to it and run assertions tests against it with the supertest package.
var mocha = require('mocha');
var request = require('supertest');
var server = require('server');
describe('test server.js', function() {
it('test GET /', function(done) {
request(server)
.get('/')
.expect(200, done);
});
});
add this code to your test case
after(function (done) {
done();
process.exit(1);
})
I'm trying to automate the update of new node modules but, npm update seems not to want to run correctly from within grunt also updating the package.json file with the new version. I want to do this regardless of what version is specified in the package.json file.
What I found till now is the node module: npm-check-updates (https://www.npmjs.com/package/npm-check-updates)
The problem is that I can't get it to work with other modules like npm-shell or npm-exec.
I've tried using npm update -D directly, but that fails too.
I'm asking if it can be done.
Here's what I use:
grunt.registerTask('update', 'Update npm modules', function() {
var exec = require('child_process').exec;
var cb = this.async();
exec('npm update -D', {}, function(err, stdout) {
console.log(stdout);
cb();
});
});
If i'm correct you're trying to update ALL of your npm packages inside of your package.json file? I would recommend using this package.
Install the package.
npm install grunt-auto-install --save-dev
Add it to your grunt tasks.
grunt.loadNpmTasks('grunt-auto-install');
Then add the configuration to your gruntfile.js
grunt.initConfig({
auto_install: {
local: {},
subdir: {
options: {
cwd: 'subdir',
stdout: true,
stderr: true,
failOnError: true,
npm: '--production'
}
}
},
});
Here is the reference:
https://www.npmjs.com/package/grunt-auto-install
AFTER YOUVE UPDATED THE PACKAGES
Update your devDependencies and dependencies automatically with a grunt task.
Install the npm module to update your packages in your dev dependencies object.
npm install --save-dev grunt-dev-update
Add it to your grunt tasks.
grunt.loadNpmTasks('grunt-dev-update');
Add your configuration to your gruntfile.
devUpdate: {
main: {
options: {
//task options go here
}
}
}
Reference:
https://www.npmjs.com/package/grunt-dev-update
I found a solution using npm-check-update (ncu) and grunt.util.spawn:
// Install NPM Updates
grunt.registerTask('update-npm', 'Update package.json and update npm modules', function() {
grunt.log.writeln('If you get an error here, run "npm install -g npm-check-updates".');
grunt.task.run('npm-write-new');
grunt.task.run('npm-update');
});
// Check for npm module updates
grunt.registerTask('npm-check', 'Check for npm modules updates', function() {
var done = this.async();
grunt.log.writeln('Checking for npm modules updates ...');
grunt.util.spawn({
cmd: 'ncu',
args: '',
opts: {
stdio: 'inherit',
}
}, function () {
grunt.log.writeln('No files were modified.');
done();
});
});
// Write new versions to packages.json
grunt.registerTask('npm-write-new', 'Write new versions to package.json', function() {
var done = this.async();
grunt.log.writeln('Checking for npm modules updates ...');
grunt.util.spawn({
cmd: 'ncu',
args: ['-u'],
opts: {
stdio: 'inherit',
}
}, function () {
grunt.log.writeln('New versions were written to "package.json".');
done();
});
});
// Update npm modules
grunt.registerTask('npm-update', 'Update npm modules', function() {
var done = this.async();
grunt.log.writeln('Installing npm modules updates ...');
grunt.util.spawn({
cmd: 'npm',
args: ['update','--loglevel','warn'],
opts: {
stdio: 'inherit',
}
}, function () {
grunt.log.writeln('NPM modules were updated.');
done();
});
});
I am running sailsjs, mocha, and babel on sails and mocha. When I run, my before function to start the sails app before running tests, I get this:
> PORT=9999 NODE_ENV=test mocha --recursive --compilers js:babel/register
lifting sails
1) "before all" hook
0 passing (757ms)
1 failing
1) "before all" hook:
Uncaught Error: only one instance of babel/polyfill is allowed
For the life of me, I can't figure out how to make mocha running babel and sails running babel at the same time work.
My before() code looks like this:
import Sails from 'sails'
// Global before hook
before(function (done) {
console.log('lifting sails')
// Lift Sails with test database
Sails.lift({
log: {
level: 'error'
},
models: {
connection: 'testMongoServer',
migrate: 'drop'
},
hooks: {
// sails-hook-babel: false
babel: false
}
}, function(err) {
if (err) {
return done(err);
}
// Anything else you need to set up
// ...
console.log('successfully lifted sails')
done();
});
});
I use sails-hook-babel and it works like a charm. Here to do it:
Install npm install sails-hook-babel --save-dev
Edit your bootstrap.js/ before function to load babel, i.e.
var Sails = require('sails'),
sails;
var options = {
loose : "all",
stage : 2,
ignore : null,
only : null,
extensions: null
};
global.babel = require("sails-hook-babel/node_modules/babel/register")(options);
before(function (done) {
Sails.lift({
//put your test only config here
}, function (err, server) {
sails = server;
if (err) return done(err);
// here you can load fixtures, etc.
done(err, sails);
});
});
after(function (done) {
// here you can clear fixtures, etc.
sails.lower(done);
});
Now you are able to use ES6 within your tests.
Here is the reference:
Babel issue at GitHub
My Blog, sorry it written in Bahasa Indonesia, use Google translate if you want to.
I am trying to run karma tests from gulp task and I am getting this error:
Error: 1
at formatError (C:\Users\Tim\AppData\Roaming\npm\node_modules\gulp\bin\gulp.js:161:10)
at Gulp.<anonymous> (C:\Users\Tim\AppData\Roaming\npm\node_modules\gulp\bin\gulp.js:187:15)
at Gulp.emit (events.js:95:17)
at Gulp.Orchestrator._emitTaskDone (C:\path\to\project\node_modules\gulp\node_modules\orchestrator\index.js:264:8)
at C:\path\to\project\node_modules\gulp\node_modules\orchestrator\index.js:275:23
at finish (C:\path\to\project\node_modules\gulp\node_modules\orchestrator\lib\runTask.js:21:8)
at cb (C:\path\to\project\node_modules\gulp\node_modules\orchestrator\lib\runTask.js:29:3)
at removeAllListeners (C:\path\to\project\node_modules\karma\lib\server.js:216:7)
at Server.<anonymous> (C:\path\to\project\node_modules\karma\lib\server.js:227:9)
at Server.g (events.js:180:16)
My system is Windows 7, nodejs version is v0.10.32, gulp version:
[10:26:52] CLI version 3.8.8
[10:26:52] Local version 3.8.9
Also, the same error I am getting on Ubuntu 12.04 LTS while on newer Ubuntu (not sure what version) and mac os it is seems to be working ok. What can cause this error?
Update 5/11/2016: Before writing comment about the fact that accepted answer hide errors, please, see first two comments to that particular accepted answer. Use it only if know what you are doing. Related info: https://github.com/karma-runner/gulp-karma/pull/15
How are you running your tests with Gulp? I came up against this issue recently on OSX, running node v0.11.14 and gulp 3.8.10, whenever there were failing tests.
Changing from the recommended:
gulp.task('test', function(done) {
karma.start({
configFile: __dirname + '/karma.conf.js',
singleRun: true
}, done);
});
To:
gulp.task('test', function(done) {
karma.start({
configFile: __dirname + '/karma.conf.js',
singleRun: true
}, function() {
done();
});
});
...got rid of this error.
Seems to be down to how gulp handles error messages when an error is signalled in a callback. See Improve error messages on exit for more information.
None of these solutions worked correctly for me using gulp 3.9.1 and karma 1.1.1. Adding a reference to gulp-util npm install --save-dev gulp-util and updating the task to the below fix the error output very nicely, while maintaining exit status correctly.
var gutil = require('gulp-util');
gulp.task('test', function (done) {
new Server({
configFile: __dirname + '/karma.conf.js',
singleRun: true
}, function(err){
if(err === 0){
done();
} else {
done(new gutil.PluginError('karma', {
message: 'Karma Tests failed'
}));
}
}).start();
});
Below is a code snippet from gulp patterns on using Karma. It's a bit similar, but also uses the newer method how to start the karma.
/**
* Start the tests using karma.
* #param {boolean} singleRun - True means run once and end (CI), or keep running (dev)
* #param {Function} done - Callback to fire when karma is done
* #return {undefined}
*/
function startTests(singleRun, done) {
var child;
var excludeFiles = [];
var fork = require('child_process').fork;
var KarmaServer = require('karma').Server;
var serverSpecs = config.serverIntegrationSpecs;
if (args.startServers) {
log('Starting servers');
var savedEnv = process.env;
savedEnv.NODE_ENV = 'dev';
savedEnv.PORT = 8888;
child = fork(config.nodeServer);
} else {
if (serverSpecs && serverSpecs.length) {
excludeFiles = serverSpecs;
}
}
var server = new KarmaServer({
configFile: __dirname + '/karma.conf.js',
exclude: excludeFiles,
singleRun: singleRun
}, karmaCompleted);
server.start();
////////////////
function karmaCompleted(karmaResult) {
log('Karma completed');
if (child) {
log('shutting down the child process');
child.kill();
}
if (karmaResult === 1) {
done('karma: tests failed with code ' + karmaResult);
} else {
done();
}
}
}
What worked for me and gave a nice formatted error message is to provide an Error instance to the done callback.
gulp.task('test', function(done) {
karma.start({
configFile: __dirname + '/karma.conf.js',
singleRun: true
}, function(result) {
if (result > 0) {
return done(new Error(`Karma exited with status code ${result}`));
}
done();
});
});
If you want to return with an error code, and want to see Karma's error output but not Gulp's (probably unrelated) stack trace:
gulp.task('test', function() {
karma.start({
configFile: __dirname + '/karma.conf.js',
singleRun: true
}, function(karmaExitStatus) {
if (karmaExitStatus) {
process.exit(1);
}
});
});
Not sure about Ubuntu, but I was getting a similar error on Windows, and installing one version back fixed it right away like this:
npm install -g gulp#3.8.8
npm install gulp#3.8.8
this is gulp's way of telling your tests have failed and that karma exited with a return code of 1. Why you would want to call done yourself and not pass the error as a message baffles me.
The right way to solve this according to Karma's documentation and https://github.com/pkozlowski-opensource, is to rely on Karma's watch mechanism rather than Gulp's:
gulp.task('tdd', function (done) {
karma.start({
configFile: __dirname + '/karma.conf.js'
}, done);
});
Note the omission of singleRun: true.
#McDamon's workaround will work for gulp.watch, but you don't want to swallow exit codes like that when running on a CI server.
Gulp is also reworking how they handle exit codes in scenarios just like this one. See https://github.com/gulpjs/gulp/issues/71 and the other dozen or so related issues.
gulp.task('test', function(done) {
karma.start({
configFile: __dirname + '/karma.conf.js',
singleRun: false
}, done);
});
passing singleRun: false argument will prevent the process from returning a value different of 0 (which would signify an error and exit gulp).
Run with singleRun: true if you only launching your test from a command line, not part of a continuous integration suite.
In case anyone else comes here, do not use the accepted solution. It will hide failed tests. If you need a quick solution to modify your gulp test task, you can use the solution found in this comment in this github thread.
gulp.src(src)
// pipeline...
.on('error', function (error) {
console.error('' + error);
});
I have a nodeunit test that tests my custom grunt task:
'use strict';
var grunt = require('grunt');
exports.when_executing_single_command = {
it_should_execute_successfully: function(test) {
test.expect(1);
grunt.initConfig({
mytask: {
success: function(data) {
test.strictEqual(data, '1');
test.done();
}
}
});
require('../src/mytask')(grunt);
grunt.registerTask('default', ['mytask']);
grunt.task.run('default');
}
};
Based on nodeunit documentation the test appears to be setup correctly, but the callback is never executed and test continues to run indefinitely.
I know that under the right conditions the callback is definitely executed, so this is not a bug in my task.
Exact same issue here.
It appears to me that grunt is queuing task calls. So if you launch your tests with a grunt nodeunit command you cannot launch another task inside your test, it will be queued and can only be run after your nodeunit task is done.
There is a solution but it doesn't fit for my case, it may apply for you :
grunt.util.spawn({
grunt: true,
args: ["your_task_name"],
opts:{
stdio: 'inherit'
}
}, function(){
// Do something
})
grunt.util.spawn