Mocha API Testing: getting 'TypeError: app.address is not a function'

Mocha API Testing: getting 'TypeError: app.address is not a function'

我的问题

我编写了一个非常简单的 CRUD API,最近我也开始编写一些使用 chaichai-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...

  });

});

还有我的 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;

附加说明

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

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

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

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

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

module.exports = server

这也可能有所帮助,并满足@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 ...', () => {

当我们 运行 mocha 在我们的节点 + typescript 无服务器项目中使用 ts-node 时,我们遇到了同样的问题。

我们的 tsconfig.json 有 "sourceMap": true 。如此生成的 .js 和 .js.map 文件会导致一些有趣的转译问题(类似于此)。当我们 运行 mocha 运行ner 使用 ts-node 时。因此,我将 sourceMap 标志设置为 false 并删除我们 src 目录中的所有 .js 和 .js.map 文件。那么问题就解决了。

如果您已经在 src 文件夹中生成了文件,下面的命令将非常有用。

find src -name ".js.map" -exec rm {} \; 找到 src -name ".js" -exec rm {} \;

上面的答案正确地解决了这个问题: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));
});

为了以防万一,如果有人用Hapijs还是会出现这个问题,因为它没有使用Express.js,所以address()函数不存在

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

使其工作的解决方法

// 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()
      })
    })
  })

我正在使用 Jest 和 Supertest,但收到了同样的错误。这是因为我的服务器需要时间来设置(设置数据库、读取配置等是异步的)。我需要使用 Jest 的 beforeAll 助手来允许异步设置为 运行。我还需要重构我的服务器以分离监听,而是使用@Whyhankee 的建议来创建测试服务器。

index.js

export async function createServer() {
  //setup db, server,config, middleware
  return express();
}

async function startServer(){
  let app = await createServer();
  await app.listen({ port: 4000 });
  console.log("Server has started!");
}

if(process.env.NODE_ENV ==="dev") startServer();

test.ts

import {createServer as createMyAppServer} from '@index';
import { test, expect, beforeAll } from '@jest/globals'
const supertest = require("supertest");
import * as http from 'http';
let request :any;

beforeAll(async ()=>{
  request = supertest(http.createServer(await createMyAppServer()));
})

test("fetch users", async (done: any) => {
  request
    .post("/graphql")
    .send({
      query: "{ getQueryFromGqlServer (id:1) { id} }",
    })
    .set("Accept", "application/json")
    .expect("Content-Type", /json/)
    .expect(200)
    .end(function (err: any, res: any) {
      if (err) return done(err);
      expect(res.body).toBeInstanceOf(Object);
      let serverErrors = JSON.parse(res.text)['errors'];
      expect(serverErrors.length).toEqual(0);
      expect(res.body.data.id).toEqual(1);
      done();
    });
});

编辑:

我在使用 data.foreach(async()=>... 时也有错误,应该在我的测试中使用 for(let x of...