I'm trying to add unit tests to my nodejs application using mocha.
I've created a dummy test endpoint '/test' which returns a string as shown below :
Test endpoint :
app.get(routeHelper.getURLPath('/test'), (req, res, next) => {
res.send('Helloo from test route !!');
next();
});
sample.test.js :
process.env.NODE_ENV = 'test';
let supertest = require("supertest");
let should = require("should");
let server = supertest.agent("http://localhost:9000");
describe('Routes', () => {
it('sample test', (done) => {
server
.get("/test")
.expect(200)
.end(function(err,res){
// console.log('***************Ressssssss******* ', res.body);
console.log('***************errrrrrrrrrrrrrr******* ', err);
res.status.should.equal(200);
res.body.error.should.equal(false);
done();
});
});
});
When I run the test, it is throwing the error shown below :
{ Error: socket hang up
at createHangUpError (_http_client.js:322:15)
at Socket.socketOnEnd (_http_client.js:425:23)
at Socket.emit (events.js:187:15)
at endReadableNT (_stream_readable.js:1094:12)
at process._tickCallback (internal/process/next_tick.js:63:19) code: 'ECONNRESET', response: undefined }
Accessing the API directly from the browser is giving the response properly. But, it's throwing this error when I run the test.
Any help to fix this will very helpful.
Related
I have this simple server to play around express and node. I am getting this error when I call a function inside the app.get() method. I have serached around the internet and still I couldn't figure it out what's going in here.
Error
http_outgoing.js:518
throw new ERR_HTTP_HEADERS_SENT('set');
^
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after
they are sent to the client
at ServerResponse.setHeader (_http_outgoing.js:518:11)
at Array.write (G:\Project\Node Projects\Automater\node_modules\finalhandler\index.js:285:9)
at listener (G:\Project\Node Projects\Automater\node_modules\on-finished\index.js:169:15)
at onFinish (G:\Project\Node Projects\Automater\node_modules\on-finished\index.js:100:5)
at callback (G:\Project\Node Projects\Automater\node_modules\ee-first\index.js:55:10)
at IncomingMessage.onevent (G:\Project\Node Projects\Automater\node_modules\ee-first\index.js:93:5)
at IncomingMessage.emit (events.js:327:22)
at endReadableNT (_stream_readable.js:1221:12)
at processTicksAndRejections (internal/process/task_queues.js:84:21) {
code: 'ERR_HTTP_HEADERS_SENT'
}
Here is my code
const express = require('express');
const app = express();
const port = process.env.PORT || 3000;
app.get('/user',(req,res,next) =>{
log(req,res,next);
res.send('user');
})
app.get('/',(req,res,next) => {
res.send('Success');
});
function log(req,res,next){
console.log('Logger !!!');
next();
}
app.listen(port, () => console.log(`listening on port ${port}!`));
You should remove res.end() because res.send(...) calls res.write, res.setHeaders, and res.end for you. When you call res.send(...) you already send response to client.
It means that the response has already been sent to the client.
You are doing 2 things: res.send('user'); res.end();
Remove res.end() and it should be good.
I'm trying to do BDD tests to cover my code, but I got this error :
I'm trying to do BDD tests to cover my code, but I got this error :
I'm trying to do BDD tests to cover my code, but I got this error :
I'm trying to do BDD tests to cover my code, but I got this error :
I'm trying to do BDD tests to cover my code, but I got this error :
app.js
"use strict";
var app = require("express")();
var pg = require("pg");
var http = require("http");
var https = require("https");
require("./config/config");
var server;
swaggerTools.initializeMiddleware(swaggerConfig, function (middleware) {
// Interpret Swagger resources and attach metadata to request - must be first in swagger-tools middleware chain
app.use(middleware.swaggerMetadata());
var sayHello = ( type ) => {
return ( ) => {
console.log( `${global.gConfig.app.name} (${global.gConfig.app.desc}) listening for ${type.toUpperCase()} connections on port ${global.gConfig.ports[type]}`);
}
}
if( global.gConfig.ports.http ) {
http.createServer(app).listen( global.gConfig.ports.http, sayHello('http') );
server=app.listen(global.gConfig.ports.http);
}
if( global.gConfig.ports.https ) {
server=app.listen(global.gConfig.ports.https);
}
});
module.exports = {
serve:server,
app:app
};
test.js
let chai = require('chai');
let expect = require('chai').expect;
let chaiHttp = require('chai-http');
var app=require('../').app;
var server=require('../').server;
let should = require('chai').should;
var request = require("supertest").agent(server);
chai.use(chaiHttp);
describe('Caracteristiques', () => {
after(function (done) {
server.close();
done();
});
it('returns an array of Carateristiques', (done) => {
//chai.request(server)
request
.get('caracteristiques')
.set('Authorization', 'Bearer token')
.end((err, res) => {
console.log("res :",res);
expect(res.status).to.equal(200);
done();
});
});
})
the error :
1) Uncaught error outside test suite:
Uncaught Error: listen EADDRINUSE :::3001
at Object._errnoException (util.js:992:11)
at _exceptionWithHostPort (util.js:1014:20)
at Server.setupListenHandle [as _listen2] (net.js:1355:14)
at listenInCluster (net.js:1396:12)
at Server.listen (net.js:1480:7)
at Function.listen (node_modules\express\lib\application.js:618:24)
at C:\Users\zya\Documents\Tdbc-api\tdbc-api\app.js:75:17
at C:\Users\zya\Documents\Tdbc-api\tdbc-api\node_modules\swagger-tools\index.js:85:7
at cbWrapper (node_modules\swagger-tools\lib\specs.js:1023:5)
at validateSwagger2_0 (node_modules\swagger-tools\lib\specs.js:1018:3)
at validateSemantically (node_modules\swagger-tools\lib\specs.js:1028:5)
at C:\Users\zya\Documents\Tdbc-api\tdbc-api\node_modules\swagger-tools\lib\specs.js:1221:7
at C:\Users\zya\Documents\Tdbc-api\tdbc-api\node_modules\swagger-tools\lib\specs.js:1061:29
at C:\Users\zya\Documents\Tdbc-api\tdbc-api\node_modules\swagger-tools\lib\specs.js:707:12
at C:\Users\zya\Documents\Tdbc-api\tdbc-api\node_modules\swagger-tools\lib\specs.js:683:9
at <anonymous>
at process._tickCallback (internal/process/next_tick.js:188:7)
at startup (bootstrap_node.js:191:16)
at bootstrap_node.js:612:3
2) Caracteristiques
returns an array of Carateristiques:
TypeError: Cannot read property 'address' of undefined
at Test.serverAddress (node_modules\supertest\lib\test.js:55:18)
at new Test (node_modules\supertest\lib\test.js:36:12)
at TestAgent.(anonymous function) [as get] (node_modules\supertest\lib\agent.js:52:15)
at Context.it (test\caracteristiques.js:31:14)
3) Caracteristiques
"after all" hook:
TypeError: Cannot read property 'close' of undefined
at Context.<anonymous> (test\caracteristiques.js:23:16)
I think the set up id good, can any one helop please ?
i think it's not working because you are trying to enable the server in the same port each time your test is executed. [Or you have your sever running while you execute your tests].
Try to shut down your server while you execute your tests.
FYI: You are exporting your server main module as "serve", then you try to acceed to it using require(path).server instead of require(path).serve;
I am new to unit testing. I have been writing test case using mocha for Nodejs. In my case need to write test case for facebook login. I have firstly tried with facebook-mock but i was not able to complete the task.This is my test case where I have used zombie,
var chai = require('chai');
var assert = chai.assert;
var server;
var Browser = require('zombie');
describe("login using social sites",function () {
this.timeout(40000);
beforeEach(function () {
server = require('../../../server').server;
browser = new Browser({ site: 'http://localhost:3000' });
});
it("should login with facebook",function (done) {
browser.visit('/auth/facebook',function (err,brw) {
if(err){
throw err;
}
assert.equal(brw.location.pathname, '/auth/facebook/callback');
done();
});
});
afterEach(function () {
server.close();
});
});
And the server.js file is,
var express = require('./config/express');
var app = express();
var server = app.listen(3000, function () {
var port = server.address().port;
console.log('Server running at %s', port);
});
module.exports = {
app : app,
server : server
};
This is the error which i have got after executing the unit test,
1) login using social sites should login with facebook:
Uncaught TypeError: connect ECONNREFUSED 127.0.0.1:3000
at G:\Janani\Tasks\CCSProject\node_modules\zombie\lib\pipeline.js:89:15
at tryCatcher (G:\Janani\Tasks\CCSProject\node_modules\zombie\node_modules\bluebird\js\release\util.js:16:23)
at Promise._settlePromiseFromHandler (G:\Janani\Tasks\CCSProject\node_modules\zombie\node_modules\bluebird\js\release\promise.js:504:31)
at Promise._settlePromise (G:\Janani\Tasks\CCSProject\node_modules\zombie\node_modules\bluebird\js\release\promise.js:561:18)
at Promise._settlePromise0 (G:\Janani\Tasks\CCSProject\node_modules\zombie\node_modules\bluebird\js\release\promise.js:606:10)
at Promise._settlePromises (G:\Janani\Tasks\CCSProject\node_modules\zombie\node_modules\bluebird\js\release\promise.js:681:18)
at Async._drainQueue (G:\Janani\Tasks\CCSProject\node_modules\zombie\node_modules\bluebird\js\release\async.js:138:16)
at Async._drainQueues (G:\Janani\Tasks\CCSProject\node_modules\zombie\node_modules\bluebird\js\release\async.js:148:10)
at Immediate.Async.drainQueues [as _onImmediate] (G:\Janani\Tasks\CCSProject\node_modules\zombie\node_modules\bluebird\js\release\async.js:17:14)
Please anyone guide me to fix this issue. And if any other specific framework if available please guide me with that. Thanks in Advance!!
I got fixed with this issue!!!
describe("login using social sites",function () {
this.timeout(40000);
beforeEach(function () {
server = require('../../../server').server;
// browser = new Browser({ site: 'http://localhost:3000' });
});
it("should login with facebook",function (done) {
Browser.visit('http://127.0.0.1:3000/auth/facebook',function (err,brw) {
if(err){
throw err;
}
brw.fill('email','aaa#gmail.com').fill('pass', 'password')
.pressButton('login', function (err,brow) {
brw.assert.success();
done();
});
});
});
afterEach(function () {
server.close();
});
});
my file structure is like this
folder_main
-server.js
-folder_tests
--serverTest.js
var expect = require("chai").expect;
var http = require('http')
describe('/', function(){
var server;
beforeEach(function () {
server = require('../server');
});
afterEach(function () {
server.close();
});
it('should return 200 status code', function(){
http.get("http://localhost:8080", function(res) {
console.log("Got response: " + res.statusCode);
expect(res.statusCode).to.equal("This isnt even a number")
})
})
})
and server.js is
var express = require('express');
var app = express();
var http = require('http');
var server = http.createServer(app);
var io = require('socket.io').listen(server);
var port = 8080;
server.listen(port);
console.log("listening on port " + port)
// router
app.get('/', function (req, res){
res.writeHead(200, {"Content-Type": "text/plain"});
res.end("Hello World\n");
});
module.exports = server;
when I run "mocha test" from the cmd line I get
✓ should return 200 status code
1) "after each" hook
1 passing (277ms) 1 failing
1) / "after each" hook:
Uncaught Error: connect ECONNRESET
at errnoException (net.js:904:11)
at Object.afterConnect [as oncomplete] (net.js:895:19)
I am confused
The first test should fail because it compares to "This isnt even a number".
I am not sure what is happening with Uncaught Error: connect ECONNRESET
Mocha tests need to use the done() callback if you are testing asynchronous code otherwise mocha will complete before your assertions run and no failures will be detected.
it('should return 200 status code', function(done){
http.get("http://localhost:8080", function(res) {
console.log("Got response: " + res.statusCode);
expect(res.statusCode).to.equal("This isnt even a number")
done()
})
})
done is setup as the first parameter to your testing function, which you then call after your assertions. If the done function is not called, mocha will timeout the test after the default of 2 seconds.
This will probably resolve your ECONNRESET issue too as your server is not being shutdown mid test/request.
It can help to always make use of done(), even when testing synchronous code so you don't fall into this trap in the future. False positives can cause hours of trouble shooting pain.
I am trying to create a simple server and a simple client with node.js using http module. Server is working fine but client is not. Please help me to find the bug...
Server Is :
var server = require('http').createServer();
server.on('request', function(req, res){
res.end("hello, world");
});
server.listen(4000);
Client Is :
var options = {
host : 'localhost',
port : 4000,
method : 'GET',
path " '/'
};
require('http').request(options, function(res){
console.log(require('util').inspect(res));
res.on('data', function(data){
console.log(data);
});
I am running them in different terminal windows as node server.js & node client.js.
I am getting below mentioned error on the client.js running terminal after around 10 mins.
events.js:72
throw er; // Unhandled 'error' event
^
Error: socket hang up
at createHangUpError (http.js:1473:15)
at Socket.socketOnEnd [as onend] (http.js:1569:23)
at Socket.g (events.js:175:14)
at Socket.EventEmitter.emit (events.js:117:20)
at _stream_readable.js:920:16
at process._tickCallback (node.js:415:13)
Thanks !
The request() method of the HTTP library will not automatically end requests, therefore they stay open, and time out. Instead, you should either end the request using req.end(), or use the get() method, which will do so automatically.
var http = require('http');
var req = http.request(options, function(res) {
// handle the resposne
});
req.end();
Or:
http.get(options, function(res) {
// handle the resposne
});