npm run script: node server.js && mocha test - node.js

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);
})

Related

In After or afterEach method it is not possible to stop the httpServer in chai-http

I have an Express http server in nodeJS and I am using chai mocha for unittest or integration tests. These tests run fine, but after the test the server should stop. But the server never stops. I have tried lot of possibitys which are commented out in the code below. I see that all functions are called but the agent.close(). is not executed or it is ignored by the server.
I have looked on these sites:
Use ChaiHttp with beforeEach or before method
How to correctly close express server between tests using mocha and chai
https://mochajs.org/#hooks
And on this site is stated that the method I am using is the right one but it is not working:
https://www.chaijs.com/plugins/chai-http/
Here is my code.
import * as chai from 'chai';
import { expect } from 'chai'
import chaiHttp = require('chai-http');
import { app } from '../../server';
//let testServer;
chai.use(chaiHttp);
chai.should();
describe('Relaties', () => {
let agent = chai.request.agent(app);
beforeEach(function (done) {
console.log('outer describe - beforeEach');
//testServer = require('../../server')
agent
.put('/api/ehrm-klantnr/medewerker/login')
.send({ email: 'admin#sfgtest.com', wachtwoord: '<secret>' })
.then(function (res) {
expect(res).to.have.cookie('SESSIONID');
done();
});
});
afterEach(function (done) {
console.log('Describe - After');
agent.close();
//delete require.cache[require.resolve( '../../server' )]
done();
//server.close();
//agent.close();
//testServer.close();
});
describe('Ophalen alle relaties met: GET /api/ehrm-klantnr/relatie', () => {
it('should get alle relaties', (done) => {
agent.get('/api/ehrm-klantnr/relatie')
.set('meta', '1')
.then(function (res) {
expect(res).to.have.status(200);
done();
});
});
});
Anybody an idea what I am doing wrong ?
I finally found the answer and it is a simple solution.
This can be solved by just adding a simple parameter to the mocha command in the npm start script line in the package.json file:
The npm start test config must be like this, and the --exit --r parameter are important:
"scripts": {
"ng": "ng",
"test": "mocha --exit -r ts-node/register **/*.spec.ts", //this is the correct config
"start-server": "./node_modules/.bin/ts-node ./server.ts",
"server": "./node_modules/.bin/nodemon -w . --ext \".ts\" --exec \"npm run start-server\""
},

Gulp Nodemon - how do I make Nodemon exit on file change

Currently I have a very simple Gulp build script:
const gulp = require('gulp');
const ts = require('gulp-typescript');
const tsProject = ts.createProject('tsconfig.json');
const del = require('del');
const nodemon = require('gulp-nodemon');
gulp.task('build-clean', function() {
return del('dist');
});
gulp.task('build', ['build-clean'], function () {
return gulp.src('src/**/*.ts')
.pipe(tsProject())
.pipe(gulp.dest('dist'));
});
gulp.task('start', ['build'], function () {
nodemon({
script: 'dist/app.js'
, ext: 'js html'
})
})
This reloads the page on changes to JS or HTML files.
This is useful for developing, but on production I want the exact opposite. If my files change, that's because of a git push to my server. That means Jenkins will run, after that's finished Jenkins will push the code to my webfolder.
I want to stop this nodemon server if Jenkins pushes the code, because a completely fresh gulp-build will be executed, including the Nodemon server.
So - how can I make nodemon exit after files change instead of restarting?
Maybe should you just use nodein production instead of nodemon
gulp.task('start', ['build'], function () {
node({
script: 'dist/app.js'
, ext: 'js html'
})
})

How do I run Jest Tests

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

Babel not working with Mocha and starting Node server

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.

Cannot read property '_host' of null when running supertest in node-inspector

I'm fairly new to the Angular world and have been using the angular-fullstack generator + Yeoman to build out a project. I'm using Sublime (not Webstorm) and have been trying to figure out how to set up the project so that I can debug the mocha tests from the terminal, but am hitting a wall.
Here's the default things.spec.js that's generated with 'yo angular-fullstack' with a debugger statement added in.
var should = require('should');
var app = require('../../app');
var request = require('supertest');
describe('GET /api/things', function() {
it('should respond with JSON array', function(done) {
request(app)
.get('/api/things')
.expect(200)
.expect('Content-Type', /json/)
.end(function(err, res) {
debugger;
if (err) return done(err);
res.body.should.be.instanceof(Array);
done();
});
});
});
By combining advice from the grunt-mocha-test documentation and this SO answer, I've updated the test script in package.json as follows:
"scripts": {
"test": "node-debug <PATH TO GRUNT-CLI>\\grunt test"
}
When I run 'npm test', node-inspector successfully boots up a browser instance and attaches the debug session to my test process. However, when I press "continue", the debugger breakpoint is NOT hit and the test fails with the following stack. Anyone have any clues as to what's causing this?
TypeError: Cannot read property '_host' of null
at ClientRequest.http.ClientRequest.onSocket (eval at WRAPPED_BY_NODE_INSPECTOR (\node_modules\node-inspector\node_modules\v8-debug\v8-debug.js:95:15), <anonymous>:381:28)
at new ClientRequest (http.js:1432:10)
at Object.exports.request (http.js:1843:10)
at Test.Request.request (\node_modules\supertest\node_modules\superagent\lib\node\index.js:615:28)
at Test.Request.end (\node_modules\supertest\node_modules\superagent\lib\node\index.js:677:18)
at Test.end (\node_modules\supertest\lib\test.js:123:7)
at Context.<anonymous> (\server\api\thing\thing.spec.js:14:8)
at Test.Runnable.run (\node_modules\grunt-mocha-test\node_modules\mocha\lib\runnable.js:196:15)
at Runner.runTest (\node_modules\grunt-mocha-test\node_modules\mocha\lib\runner.js:374:10)
at Runner.runTests.next (\node_modules\grunt-mocha-test\node_modules\mocha\lib\runner.js:452:12)
This looks like a bug in Node Inspector.
https://github.com/node-inspector/node-inspector/issues/698

Resources