简体   繁体   中英

Error while testing NodeJS and MongoDB stack using Mocha and Chai

Right now, I'm running Mocha tests and am getting the following error:

  Error: connect ECONNREFUSED 127.0.0.1:27017
    at Object.exports._errnoException (util.js:873:11)
    at exports._exceptionWithHostPort (util.js:896:20)
    at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1077:14)

I assume it's because I am unable to connect to port 27017 because I did not include:

var express = require('express')
var app = express()

However, what is particularly confusing to me is how I connect by test to MongoDB so I can create fake records for testing and then destroy them. If anyone can show me (with an example please) how to do it, that would be awesome!

Thanks again.

The error is coming may be the mongo server is not running or from more than one server trying to listen on same port. Also for test environment only can create different folder or use different port. So that can delete the folder once test case is over

In server.js

if(process.env === 'test')
{
    mongoport = 57017;
}
else
{
    mongoport = 27017;
}
mongoUrl = "mongodb://localhost:"+mongoport+"/student"
// use the mongodb url

In test.js

//on start of test case

var fs = require('fs-extra');
fs.removeSync("test/db/");
fs.ensureDirSync("test/db/");
//ur test case definition

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM