摩卡APItesting:得到'TypeError:app.address不是一个函数'

我的问题

我已经编写了一个非常简单的CRUD API,最近我也开始编写一些使用chaichai-httptesting,但是在使用$ mocha运行我的testing时遇到了问题。

当我运行testing时,在shell上出现以下错误:

TypeError: app.address is not a function

我的代码

这里是我的一个testing( /tests/server-test.js )的示例:

 var chai = require('chai'); var mongoose = require('mongoose'); var chaiHttp = require('chai-http'); var server = require('../server/app'); // my express app var should = chai.should(); var testUtils = require('./test-utils'); chai.use(chaiHttp); describe('API Tests', function() { before(function() { mongoose.createConnection('mongodb://localhost/bot-test', myOptionsObj); }); beforeEach(function(done) { // I do stuff like populating db }); afterEach(function(done) { // I do stuff like deleting populated db }); after(function() { mongoose.connection.close(); }); describe('Boxes', function() { it.only('should list ALL boxes on /boxes GET', function(done) { chai.request(server) .get('/api/boxes') .end(function(err, res){ res.should.have.status(200); done(); }); }); // the rest of the tests would continue here... }); }); 

和我的express应用程序文件( /server/app.js ):

 var mongoose = require('mongoose'); var express = require('express'); var api = require('./routes/api.js'); var app = express(); mongoose.connect('mongodb://localhost/db-dev', myOptionsObj); // application configuration require('./config/express')(app); // routing set up app.use('/api', api); var server = app.listen(3000, function () { var host = server.address().address; var port = server.address().port; console.log('App listening at http://%s:%s', host, port); }); 

和( /server/routes/api.js ):

 var express = require('express'); var boxController = require('../modules/box/controller'); var thingController = require('../modules/thing/controller'); var router = express.Router(); // API routing router.get('/boxes', boxController.getAll); // etc. module.exports = router; 

额外的笔记

我已经尝试在运行testing之前在/tests/server-test.js文件中注销servervariables:

 ... var server = require('../server/app'); // my express app ... console.log('server: ', server); ... 

我的结果是一个空的对象: server: {}

       

网上收集的解决方案 "摩卡APItesting:得到'TypeError:app.address不是一个函数'"

您不会在应用程序模块中导出任何内容。 尝试添加到您的app.js文件:

 module.exports = server 

这也可能有所帮助,并满足更改应用程序代码以适应testing的@dman要点。

根据需要向本地主机和端口发送请求chai.request('http://localhost:5000')

代替

chai.request(server)

这固定了我使用Koa JS(v2)和ava js的同样的错误信息。

导出由app.listen(3000)返回的http.Server对象而非仅仅是函数app ,否则您将得到TypeError: app.address is not a function

例:

index.js

 const koa = require('koa'); const app = new koa(); module.exports = app.listen(3000); 

index.spec.js

 const request = require('supertest'); const app = require('./index.js'); describe('User Registration', () => { const agent = request.agent(app); it('should ...', () => {