我正在尝试使用 Mocha 为我正在开发的 REST API 编写测试。我发现了允许我发出 HTTP 请求的 Superagent。我正在使用一个 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)
但是,此错误仅有时会出现。1/5 次,测试将毫无问题地通过。这让我觉得测试有时会在app
完全加载之前运行。
或者,如果我在单独的会话中运行应用程序并将 URL 传递给request
,如下所示,那么它每次都有效:
request = request('http://localhost:3000')
这是原因吗?app
如果是这样,我怎样才能在完全加载后才运行测试?