Reputation: 1734
I have an express api I am developing and am trying to use this project to learn all the best practices for express. That being said I want to write unit tests for my endpoints. I have been trying to figure out how to run my development server as well as run my mocha tests in watch mode. This issue is that since mocha
and nodemon
are trying to restart/run at the same time I will get varying results on my tests which kinda defeats the purpose of having it in watch mode.
I will a variety of the following errors:
1) GET /user/:userId Status Code 200:
Uncaught Error: connect ECONNREFUSED 127.0.0.1:3000
at Object.exports._errnoException (util.js:1050:11)
at exports._exceptionWithHostPort (util.js:1073:20)
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1097:14)
1) GET /user/:userId Status Code 200:
Uncaught Error: socket hang up
at createHangUpError (_http_client.js:302:15)
at Socket.socketOnEnd (_http_client.js:394:23)
at endReadableNT (_stream_readable.js:975:12)
at _combinedTickCallback (internal/process/next_tick.js:80:11)
at process._tickCallback (internal/process/next_tick.js:104:9)
I am assuming that these errors stem from either mocha trying to initialize another instance of my application which is already running or that the tests are run before the server is given a chance to restart. (I think this because it will sometimes run successfully)
I have to think this is a fairly common use case so I would like to know what the standard approach for doing this sort of thing is.
scripts in package.json
"scripts": {
"test": "mocha --compilers js:babel-register --watch",
"start": "nodemon src/index.js --exec babel-node --presets es2015,stage-2"
}
the failing user/userId
unit test:
import http from 'http'
import assert from 'assert'
describe('GET /user/:userId', () => {
it('Status Code 200', done => {
http.get('http://localhost:3000/user/1', res => {
assert.equal(200, res.statusCode)
done()
})
})
})
src/index.js
import express from 'express'
import User from './controllers/user'
const app = express()
app.get('/user/:userId',new User().getUser)
export default app.listen(3000)
Upvotes: 2
Views: 759
Reputation: 1029
I had this problem too. I looked and nodemon's git page and found this nodemon config
You can ask nodemon to ignore test file saves and so it does not restart and get in the way of test.
This only really solved my problem when changing test files though.
Another solution I used was to run
nodemon src/app.js --exec "mocha"
This takes care of rerunning the tests each time the server is restarted.
Upvotes: 3