Mocha API测试:获取'TypeError:app.address不是函数'

cha*_*nie 88 javascript mocha.js node.js express chai

我的问题

我编写了一个非常简单的CRUD API,我最近开始编写一些使用的测试chai,chai-http但是在运行我的测试时遇到了问题$ mocha.

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

TypeError: app.address is not a function

我的守则

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

  });

});
Run Code Online (Sandbox Code Playgroud)

我的expressapp文件(/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);
});
Run Code Online (Sandbox Code Playgroud)

和(/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;
Run Code Online (Sandbox Code Playgroud)

额外的笔记

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

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

console.log('server: ', server);
...
Run Code Online (Sandbox Code Playgroud)

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

xer*_*iee 189

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

module.exports = server
Run Code Online (Sandbox Code Playgroud)

  • 我唯一的问题是应该永远不要改变应用程序代码以适应测试. (26认同)
  • 我这样做,我仍然得到错误. (7认同)

Kim*_*ern 32

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

例:

index.js

const koa = require('koa');
const app = new koa();
module.exports = app.listen(3000);
Run Code Online (Sandbox Code Playgroud)

index.spec.js

const request = require('supertest');
const app = require('./index.js');

describe('User Registration', () => {
  const agent = request.agent(app);

  it('should ...', () => {
Run Code Online (Sandbox Code Playgroud)

  • 你应该在你的答案中包含_why_"重要的是导出`http.Server`对象". (2认同)

Sky*_*ard 27

这也可以帮助并满足@dman改变应用程序代码以适应测试的要点.

根据需要向localhost和port发出请求 chai.request('http://localhost:5000')

代替

chai.request(server)

这修复了我使用Koa JS(v2)和ava js时出现的相同错误消息.

  • 执行此操作后,错误不会出现,但是获取数据将变为空并且状态码200正常. (3认同)

Why*_*kee 10

上面的答案正确地解决了这个问题:supertest想要http.Server继续工作。但是,调用app.listen()获取服务器也会启动侦听服务器,这是不好的做法且没有必要。

您可以使用http.createServer()以下方法解决此问题:

import * as http from 'http';
import * as supertest from 'supertest';
import * as test from 'tape';
import * as Koa from 'koa';

const app = new Koa();

# add some routes here

const apptest = supertest(http.createServer(app.callback()));

test('GET /healthcheck', (t) => {
    apptest.get('/healthcheck')
    .expect(200)
    .expect(res => {
      t.equal(res.text, 'Ok');
    })
    .end(t.end.bind(t));
});

Run Code Online (Sandbox Code Playgroud)


小智 5

以防万一,如果有人使用Hapijs,问题仍然会发生,因为它不使用Express.js,因此address()函数不存在。

TypeError: app.address is not a function
      at serverAddress (node_modules/chai-http/lib/request.js:282:18)
Run Code Online (Sandbox Code Playgroud)

使其发挥作用的解决方法

// this makes the server to start up
let server = require('../../server')

// pass this instead of server to avoid error
const API = 'http://localhost:3000'

describe('/GET token ', () => {
    it('JWT token', (done) => {
       chai.request(API)
         .get('/api/token?....')
         .end((err, res) => {
          res.should.have.status(200)
          res.body.should.be.a('object')
          res.body.should.have.property('token')
          done()
      })
    })
  })
Run Code Online (Sandbox Code Playgroud)


Ami*_*neh 5

app在主 API 文件末尾导出,例如index.js.

module.exports = app;
Run Code Online (Sandbox Code Playgroud)