I'm using mocha.js and supertest.js to test the requests of my json server on express.js. These are my imports:
request = require('supertest')
assert = require('assert') # Node assert
app = require('../app') # Vanilla express app
This is my request implementation in the express app:
app.get '/user/:id', (req, res) ->
res.json {}
and this is my test:
describe 'GET /user/:id', ->
it 'should return the user data if user found', (done) ->
request(app)
.get("/user/some_id")
.end((err, res) ->
assert.equal('test', 'test')
done()
)
This works, but if I change my request to:
app.get '/user/:id', (req, res) ->
User.findById req.param('id'), (err, doc) ->
res.json {}
the mocha test just times out. I'm guessing this has something to do with the fact that the find is async and the test doesn't wait for it to finish. How do I solve this?
Try to increase the timeout:
mocha --timeout 5000
The default is 2000 ms and might be too short. From the documentation .
Switching to https://github.com/mikeal/request/ solved it. I'm now doing
This is my test now:
describe 'GET /user/:id', ->
it 'should return the user data if user found', (done) ->
request.get(
'http://localhost:31000/user/500d365abb75e67d0c000006'
, (err, res, body) ->
json = JSON.parse body
assert.equal(res.statusCode, 200)
assert.equal(json._id, '500d365abb75e67d0c000006')
done()
)
Everything is working as expected now, but I still want to know if it's possible to use supertest or vows for this.
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.