Jest를 이용하여 typescript에서 express server 실행 테스트
프로젝트를 하면서 test를 한 번 만들어 보고 싶어서 jest를 사용하여 먼저 server 실행 테스트를 만들어 보았다
jest에서 typescript를 실행하기 위한 ts-jest와 request를 사용하기 위해 supertest 모듈, jest의 type, supertest의 type 모듈을 설치한다
npm install --save-dev ts-jest supertest @types/jest @type/supertest jest typescript
__test__폴더를 만들고 테스트할 파일 이름은 {파일 이름}.test.ts로 만든다.
package.json에서 jest 설정 정보를 넣는다.
{
"jest": {
"transform": {
"^.+\\.ts$": "ts-jest"
},
"testRegex": "\\.test\\.ts$",
"moduleFileExtensions": [
"ts",
"tsx",
"js",
"json"
],
"globals": {
"ts-jest": {
"diagnostics": true
}
}
},
}
실행 시킬 script
"scripts": {
"test": "jest --detectOpenHandles --forceExit"
},
express는 listen하면 이벤트가 계속 열려있어 종료되지 문제가 있기때문에 --detectOpenHandles로 열려있는 리소스를 모두 닫아주고, --forceExit로 테스트가 끝나면 강제 종료를 해주는 옵션을 추가해준다.
src/main.ts
import express, { Request, Response, Application } from 'express';
const app: Application = express();
const PORT: number = Number(process.env.PORT) || 4000;
app.get('/', (req: Request, res: Response) => {
res.status(200).send('Server Success');
});
app.listen(PORT, () => {
console.log(`Server listen on PORT ${PORT}`);
});
export default app;
server.test.ts
import request from 'supertest';
import app from '../src/main';
describe('Test the root path', () => {
test('It should response the GET method', async done => {
const response = await request(app).get('/');
expect(response.status).toEqual(200);
done();
});
});
npm test 로 실행
제일 간단한 테스트를 작성해보았으니 이제 먼저 작성된 코드들에 대해 조금씩 테스트를 작성해볼 예정이다.
'Project > TIL' 카테고리의 다른 글
20.03.24 ShareBook TIL (0) | 2020.03.25 |
---|---|
20.03.23 ShareBook TIL (0) | 2020.03.24 |
20.03.21 ShareBook TIL (0) | 2020.03.22 |
20.03.20 ShareBook TIL (0) | 2020.03.20 |
20.03.19 ShareBook TIL (0) | 2020.03.20 |