我正在尝试使用Mocha为我正在开发的REST API编写测试。我发现Superagent可以让我进行HTTP请求。我正在使用一个Express应用程序,将其传递给Superagent,但是当尝试以这种方式传入Express应用程序运行这些测试时,出现了有关Mongoose的奇怪错误。以下是我的测试代码:
var
// Node modules
mongoose = require('mongoose')
, async = require('async')
, should = require('should')
, request = require('superagent')
, app = require('../../app_mocked')
, Link = mongoose.model('Link')
request = request(app)
describe('Links resource', function () {
var userId = '50dc81654dca01006b000005'
, linkId
, sampleLink = {
'uri': 'http://test.com/',
'meta': {
'title': 'Test',
'desc': 'Test link desc'
},
'shares': [{
'uid': userId,
'date': new Date(),
'message': 'Test link message'
}]
}
it('POST /api/users/:id/links', function (done) {
request(app).post('/api/users/' + userId + '/links')
.send(sampleLink)
.end(function (err, res) {
res.should.have.status(200)
res.body.should.have.property('id')
linkId = res.body.id
done()
})
})
it('GET /api/users/:id/links', function (done) {
request(app).get('/api/users/50dc81654dca01006b000005/links')
.end(function (err, res) {
res.should.have.status(200)
res.body.should.have.lengthOf(1)
done()
})
})
})
我得到的错误信息如下:
1) Links resource POST /api/users/:id/links:
TypeError: Cannot call method 'update' of null
at MongoStore.MONGOSTORE.set (/Users/Oliver/Development/Personal/Reader/node_modules/connect-mongodb/lib/connect-mongodb.js:146:15)
at Session.save (/Users/Oliver/Development/Personal/Reader/node_modules/express/node_modules/connect/lib/middleware/session/session.js:63:25)
at ServerResponse.res.end (/Users/Oliver/Development/Personal/Reader/node_modules/express/node_modules/connect/lib/middleware/session.js:280:19)
at ServerResponse.res.send (/Users/Oliver/Development/Personal/Reader/node_modules/express/lib/response.js:149:8)
at ServerResponse.res.json (/Users/Oliver/Development/Personal/Reader/node_modules/express/lib/response.js:191:15)
at ServerResponse.res.send (/Users/Oliver/Development/Personal/Reader/node_modules/express/lib/response.js:117:21)
at Promise.exports.create (/Users/Oliver/Development/Personal/Reader/server/resources/links.js:29:9)
然而,这个错误有时只会出现。每五次测试中,有一次测试能够正常通过。这让我想到,在
app
完全加载之前,有时候测试会运行。或者,如果我在单独的会话中运行应用程序,并将URL传递给
request
,如下所示,则每次都可以正常工作:
request = request('http://localhost:3000')
这是原因吗?如果是这样,那么我该如何在app
完全加载后再运行测试呢?