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

时间:2015-11-29 19:12:24

标签: javascript node.js express mocha chai

我的问题

我编写了一个非常简单的CRUD API,我最近开始使用chaichai-http对一些测试进行编码,但是在使用{{1}运行测试时遇到了问题}。

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

$ mocha

我的代码

以下是我的一项测试( /tests/server-test.js )的示例:

TypeError: app.address is not a function

我的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... }); }); 个应用文件( /server/app.js ):

express

和( /server/routes/api.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);
});

额外备注

在运行测试之前,我已尝试在 /tests/server-test.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; 变量:

server

我的结果是一个空对象:... var server = require('../server/app'); // my express app ... console.log('server: ', server); ...

7 个答案:

答案 0 :(得分:171)

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

module.exports = server

答案 1 :(得分:30)

导出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);

index.spec.js

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

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

  it('should ...', () => {

答案 2 :(得分:26)

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

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

而不是

chai.request(server)

这修复了我使用Koa JS(v2)和ava js。

时出现的相同错误消息

答案 3 :(得分:0)

当我们在节点+无脚本打字机项目中使用ts-node运行mocha时,我们遇到了同样的问题。

我们的tsconfig.json具有“ sourceMap”:true。如此生成的.js和.js.map文件会引起一些有趣的转码问题(与此类似)。当我们使用ts-node运行摩卡赛跑者时。因此,我将sourceMap标志设置为false,并删除了src目录中的所有.js和.js.map文件。然后问题就解决了。

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

查找src -name“ .js.map” -exec rm {} \; 找到src -name“ .js” -exec rm {} \;

答案 4 :(得分:0)

以上答案正确解决了该问题: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));
});

答案 5 :(得分:0)

以防万一,如果有人使用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()
      })
    })
  })

答案 6 :(得分:0)

我正在使用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...

相关问题