태그 보관물: mocha

mocha

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



답변

앱 모듈에서 아무것도 내 보내지 않습니다. 다음을 app.js 파일에 추가해보십시오.

module.exports = server

답변

함수 대신에서 http.Server반환 된 객체
를 내보내는 것이 중요합니다 . 그렇지 않으면 .app.listen(3000)appTypeError: 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 ...', () => {

답변

이것은 또한 도움이 될 수 있으며 테스트에 맞게 응용 프로그램 코드를 변경하는 @dman 포인트를 충족시킵니다.

필요에 따라 localhost 및 포트에 요청하십시오.

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));
});

답변

노드 + typescript 서버리스 프로젝트에서 ts-node를 사용하여 mocha를 실행할 때 동일한 문제가 발생했습니다.

tsconfig.json에는 “sourceMap”: true가 있습니다. 이렇게 생성 된 .js 및 .js.map 파일은 몇 가지 재미있는 트랜스 파일 문제를 유발합니다 (이와 유사). ts-node를 사용하여 mocha runner를 실행할 때. 따라서 sourceMap 플래그를 false로 설정하고 src 디렉터리에있는 모든 .js 및 .js.map 파일을 삭제합니다. 그러면 문제가 사라졌습니다.

src 폴더에 이미 파일을 생성했다면 아래 명령이 정말 도움이 될 것입니다.

찾기 src -name ” .js.map”-exec rm {} \; 찾기 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()
      })
    })
  })

답변