Mocha API 测试:获取'TypeError: app.address is not a function'我的问题

2022-08-30 04:35:46

我的问题

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

当我运行测试时,我在shell上收到以下错误:

类型错误:app.address 不是函数

我的代码

以下是我的一个测试(/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...

  });

});

我的应用文件(/服务器/应用.js):express

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;

额外注意事项

在运行测试之前,我尝试注销/tests/server-test.js文件中的变量:server

...
var server = require('../server/app'); // my express app
...

console.log('server: ', server);
...

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


答案 1

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

module.exports = server

答案 2

重要的是导出 返回的对象,而不仅仅是函数,否则你会得到.http.Serverapp.listen(3000)appTypeError: app.address is not a function

例:

索引.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 ...', () => {