Chai Http Post : save entity to mongodb Error: read ECONNRESET
Your first problem is caused by the app.listen
function: this is an async function so when you import your main server file you can't be sure it's running.
Then, the chai http lib documantation say:
You may use a function (such as an express or connect app) or a node.js http(s) server as the foundation for your request. If the server is not running, chai-http will find a suitable port to listen on for a given test.
So, I suggest you to separate your express app and server using two files: in this way you can import your express app in your tests without external async functions to be handled.
This is a minimal example of the suggested structure:
File app.js
:
const app = express();app.get('/', function(req, res) { res.status(200);});module.exports = app
File bin/app
(file with no extension):
#!/usr/bin/env node// the above line is required if you want to make it directly executable// to achieve this you need to make it executable using "chmod +x bin/app" from you shell, but it's an optional only required if you want to run it using "./bin/app" without an npm script.var app = require('../app');var http = require('http');app.set('port', process.env.PORT || '3000');var server = http.createServer(app);
Then update your package.json file with a new run script:
"scripts": { //... "start-app": "node ./bin/app",}
Now you can run you app using npm run start-app
. Your test code should remain the same, imporing only the app.js
file with a require
command.