Reputation: 652
I have written the following script (server.js):
var express = require('express'),
app = express(),
server;
app.get('/', function (request, response) {
response.send('This is the main page.\n');});
exports.listen = function (port){
server = app.listen(port, function () {
console.log('Server available listening at: ' + port);}) };
exports.close = function () {
server.close(function (){
console.log('Server Closed')}); };
and the following Mocha unit test (test.js):
var server = require ('./server'),
assert = require ('assert'),
http = require ('http');
var port = 8085;
describe('server', function () {
before(function () {
server.listen(port)});
after(function () {
server.close();}); });
describe('Server status and Message', function () {
it('status response should be equal 200', function (done) {
http.get('http://127.0.0.1:8085', function (response) {
assert.equal(response.statusCode, 200);
done(); }); }); });
When I run the test.js passing either 'localhost:8085' or '127.0.0.1:8085' to http client, with whatever port, Mocha show the following error:
1) Server status and Message status response should be equal 200:
Uncaught Error: connect ECONNREFUSED
at exports._errnoException (util.js:746:11)
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:983:19)
But I can connect the server perfectly via http client wiht the same localhost url (listener.js):
var server = require('./server');
var http = require('http');
var url = 'http://localhost:8085';
var content = function(response){
response.setEncoding("utf8");
response.on("data", function(data) {
console.log(data)});}
server.listen(8085);
setTimeout(function (){server.close();}, 3000)
http.get(url, content);
I have tried running the unit test with others internet url's as 'https://www.google.com.co/' (the test doesn't pass but works) and the test runs correctly.
Could you help me with this issue. Thanks you a lot.
Upvotes: 1
Views: 1687
Reputation: 259
You're accidentally running two sets of tests. Move the second describe() inside the first one so it can rely on the before() hook, like this:
var server = require ('./server'),
assert = require ('assert'),
http = require ('http');
var port = 8085;
describe('server', function () {
before(function () {
server.listen(port);
});
after(function () {
server.close();
});
describe('Server status and Message', function () {
it('status response should be equal 200', function (done) {
http.get('http://127.0.0.1:8085', function (response) {
assert.equal(response.statusCode, 200);
done();
});
});
});
});
Upvotes: 1