我正在尝试使用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)
但是,此错误有时仅出现。 1/5次,测试通过没有问题。这让我觉得测试有时会在app
完全加载之前运行。
或者,如果我在一个单独的会话中运行该应用,并将该网址传递给request
,如下所示,则每次都有效:
request = request('http://localhost:3000')
app
完全加载后运行测试?
答案 0 :(得分:10)
事实证明,在运行测试之前,我必须指定一个before
测试来等待MongoDB连接打开。
before(function (done) {
mongoose.connection.on('open', done)
})