I'm trying to run my app tests with mocha and supertest but I always get Error: connect ECONNREFUSED.
app.js code:
var express = require('express'), mongoose = require('mongoose'), fs = require('fs'), config = require('./config/config'); mongoose.connect(config.db); var db = mongoose.connection; db.on('error', function () { throw new Error('unable to connect to database at ' + config.db); }); var modelsPath = __dirname + '/app/models'; fs.readdirSync(modelsPath).forEach(function (file) { if (file.indexOf('.js') >= 0) { require(modelsPath + '/' + file); } }); var app = express(); require('./config/express')(app, config); require('./config/routes')(app); app.listen(config.port); exports.app = app; console.log('LISTEN ON http://localhost:3000/')
test.js code:
var should = require('should'); var assert = require('assert'); var request = require('supertest'); var mongoose = require('mongoose'); var app = require('../../../app').app; describe('Categories', function() { it('- POST is testing', function(done) { request(app) .post('http://localhost:3000/categories') .send({title:'test', text:'test'}) .end(function(e, res) { console.log(e, res); }); }); });
Test output:
LISTEN ON http://localhost:3000/ Categories { [Error: connect ECONNREFUSED] code: 'ECONNREFUSED', errno: 'ECONNREFUSED', syscall: 'connect' } undefined 1) - POST is testing 0 passing (2s) 1 failing Done, but with warnings.
Could you give any clue why this happend?
Thank you in advance!
Topicus
ECONNREFUSED means no process is listening at the given address and port.
SuperTest is a Node. js library that helps developers test APIs. It extends another library called superagent, a JavaScript HTTP client for Node. js and the browser. Developers can use SuperTest as a standalone library or with JavaScript testing frameworks like Mocha or Jest.
Mocha has several hooks, including before, after, beforeEach, and afterEach. They make it possible to intercept tests before or after the test run and to perform specific tasks. For example, the beforeEach hook intercepts your test right before each test in a suite is run.
The problem was the path. Replacing "localhost:3000/categories" by this "/categories" all works fine.
Working example:
describe('Categories', function() { it('- POST is testing', function(done) { request(app) .post('/categories') .send({title:'test', text:'test'}) .end(function(e, res) { console.log(e, res); }); }); });
I'm facing same problem, and find out the problem is- only the path url. Path should be in this way -
.post('/categories')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With