Mocha API 테스트: 'TypeError: app.address is not function' 가져오기
마이이슈
저는 아주 간단한 CRUD API를 코딩했고 최근에 코딩을 시작했습니다. 또한 몇가지 테스트는chai
그리고.chai-http
테스트를 실행할 때 문제가 있습니다.$ mocha
.
테스트를 실행하면 셸에서 다음 오류가 발생합니다.
TypeError: app.address가 함수가 아닙니다.
마이코드
다음은 내 테스트(/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/hosts/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;
가외음
로그아웃 해봤습니다.server
테스트를 실행하기 전에 /http/server-test.js 파일의 변수:
...
var server = require('../server/app'); // my express app
...
console.log('server: ', server);
...
그리고 나는 그 결과를 빈 물체로 생각합니다.server: {}
.
앱 모듈에서 아무것도 내보내지 않습니다.app.js 파일에 추가해 보십시오.
module.exports = server
제품을 수출하는 것이 중요합니다.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 ...', () => {
이를 통해 응용 프로그램 코드를 테스트에 맞게 변경하는 @dman 포인트를 충족할 수도 있습니다.
필요에 따라 로컬 호스트 및 포트에 요청합니다. chai.request('http://localhost:5000')
대신에
chai.request(server)
Koa JS(v2)와 avajs를 사용한 것과 같은 오류 메시지를 수정했습니다.
위의 답변은 문제를 정확하게 해결합니다.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()
})
})
})
내보내기app
메인 API 파일의 끝에 다음과 같이.index.js
.
module.exports = app;
node + 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" -execrm {} \; src -name.js" -execrm {} \;
Jest와 Supertest를 사용하고 있는데 같은 오류가 발생했습니다.서버가 셋업에 시간이 걸리기 때문입니다(셋업 db, read config 등과 비동기화됩니다).저는 제스트의 것을 사용해야 했습니다.beforeAll
helper: 비동기 설정을 실행할 수 있도록 합니다.또한 서버를 리팩터링하여 듣기를 분리하고 대신 @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...
내 시험에 있어서는
서버가 아닌 앱을 내보내야 합니다.슈퍼테스트는 서버가 아닌 앱을 가져갑니다.
module.exports = app;
언급URL : https://stackoverflow.com/questions/33986863/mocha-api-testing-getting-typeerror-app-address-is-not-a-function
'programing' 카테고리의 다른 글
NSURL 연결에 대해 Xcode 4 경고 "식 결과가 사용되지 않음" (0) | 2023.09.09 |
---|---|
PHP, 계속; for each() { for each() { (0) | 2023.09.09 |
특정 SQL 오류 코드를 가져오거나 PHP의 PDO로 잠금 시간 초과를 식별하시겠습니까? (0) | 2023.09.09 |
CSS 자식 대 후손 선택기 (0) | 2023.09.09 |
css 파일을 넣거나 넣어도 뭐가 달라요? (0) | 2023.09.09 |