developer tip

Mocha API 테스트 : 'TypeError : app.address is not a function'발생

optionbox 2020. 9. 13. 10:21
반응형

Mocha API 테스트 : 'TypeError : app.address is not a function'발생


내 문제

나는 아주 간단한 CRUD API를 코딩했는데 나는 최근에 사용하여도 몇 가지 테스트를 코딩 시작했습니다 chaichai-http하지만 내 테스트를 실행할 때이 문제에 봉착했습니다 $ mocha.

테스트를 실행할 때 셸에서 다음 오류가 발생합니다.

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: {}입니다.


You don't export anything in your app module. Try adding this to your app.js file:

module.exports = server

It's important to export the http.Server object returned by app.listen(3000) instead of just the function app, otherwise you will get TypeError: app.address is not a function.

Example:

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

This may also help, and satisfies @dman point of changing application code to fit a test.

make your request to the localhost and port as needed chai.request('http://localhost:5000')

instead of

chai.request(server)

this fixed the same error message I had using Koa JS (v2) and ava js.


The answers above correctly address the issue: supertest wants an http.Server to work on. However, calling app.listen() to get a server will also start a listening server, this is bad practice and unnecessary.

You can get around by this by using 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));
});


We had the same issue when we run mocha using ts-node in our node + typescript serverless project.

Our tsconfig.json had "sourceMap": true . So generated, .js and .js.map files cause some funny transpiling issues (similar to this). When we run mocha runner using ts-node. So, I will set to sourceMap flag to false and deleted all .js and .js.map file in our src directory. Then the issue is gone.

If you have already generated files in your src folder, commands below would be really helpful.

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

참고URL : https://stackoverflow.com/questions/33986863/mocha-api-testing-getting-typeerror-app-address-is-not-a-function

반응형