繁体   English   中英

Mocha API 测试:得到“TypeError:app.address 不是函数”

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

我的问题

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

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

类型错误:app.address 不是 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);
...

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

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

module.exports = server

导出app.listen(3000)返回的http.Server对象而不仅仅是函数app ,否则你会得到TypeError: 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 ...', () => {

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

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

代替

chai.request(server)

这修复了我在使用 Koa JS (v2) 和 ava js 时遇到的相同错误消息。

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

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

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

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

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

以防万一,如果有人使用 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 的建议来创建测试服务器。

索引.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();

测试文件

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...

在主 API 文件(如index.js )的末尾导出app

module.exports = app;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM