在摩卡testing中使用Superagent / Supertest和Express app

我正在尝试使用Mocha为我正在开发的REST API编写testing。 我发现Superagent让我做HTTP请求。 我正在使用一个Express应用程序,我将它传递给Superagent,但是当试图以这种方式传递Express应用程序来运行这些testing时,我得到关于Mongoose的奇怪错误。 这是我的testing代码:

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次,testing通过没有问题。 这使我认为testing有时在app完全加载之前运行。

或者,如果我在单独的会话中运行应用程序,并只传递URL request ,如下所示,那么它每次都有效:

request = request('http://localhost:3000')

这是为什么? 如果是这样,一旦app已经完全加载,我怎么才能运行testing?

       

网上收集的解决方案 "在摩卡testing中使用Superagent / Supertest和Express app"