250x250
Notice
Recent Posts
Recent Comments
- Today
- Total
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |
Tags
- single quote
- flutter
- atlas
- wil
- await
- Nodejs
- moment
- certbot
- TailwindCSS
- JavaScript
- jsonwebtoken
- AWS
- css
- sequelize
- clipBehavior
- mongodb
- Find
- findByIdAndDelete
- nginx
- EC2
- MYSQL
- async
- Node.js
- til
- mongoose
- RDS
- Express
- double quote
- https
- TypeScript
Link
Archives
기억 휘발 방지소
Jest를 이용하여 API 테스트코드 작성하기 (초간단) 본문
728x90
반응형
Jest는 페이스북에서 만들어 React와 더불어 많은 자바스크립트 개발자들로부터 좋은 반응을 얻고 있는 테스팅 라이브러리이다.
출시 초기에는 프론트엔드에서 주로 쓰였지만 최근에는 백엔드에서도 기존의 자바스크립트 테스팅 라이브러리를 대체하고 있다.
📌 설치
npm install --save-dev jest supertest
📌 테스트
서버를 하나 만들어주었다.
// app.js
const express = require('express');
const app = express();
app.get('/', (req, res, next) => {
res.status(200).json({
message: 'hello world',
});
});
module.exports = app;
그리고 테스트를 하기 위한 파일을 하나 만들고 다음과 같이 작성해주었다.
// app.spec.js
const request = require('supertest');
const app = require('../src/app');
it('GET / 성공 시 status code 200을 반환', async () => {
const response = await request(app).get('/');
expect(response.statusCode).toBe(200);
});
마지막으로 package.json에서 script를 수정했다.
"scripts": {
"test": "jest"
},
실행방법은 npm test를 터미널에 입력하여 실행하면 된다.
실행시 다음과 같이 나오면 성공!
📌 오류해결
처음 테스트를 할 때 app.js 파일을 다음과 같이 작성했었는데 그랬더니 에러가 발생했다.
const express = require('express');
const app = express();
app.get('/', (req, res, next) => {
res.status(200).json({
message: 'hello world',
});
});
app.listen(8080, () => {
console.log(`App listening on port 8080`);
});
module.exports = app;
app.js에서 app.listen을 다른 파일로 옮김으로써 해결할 수 있었다.
결과적으로 두 개의 파일이 된 것이다.
// app.js
const express = require('express');
const app = express();
app.get('/', (req, res, next) => {
res.status(200).json({
message: 'hello world',
});
});
module.exports = app;
// server.js
const app = require('./app');
app.listen(8080, () => {
console.log(`App listening on port 8080`);
});
당연히 서버 실행은 server.js로 해야한다.
728x90
반응형
'Web > Node.js' 카테고리의 다른 글
[Node.js] String의 Bytes Length 구하기 (1) | 2022.05.20 |
---|---|
Express + Nginx (with 윈도우) (0) | 2022.04.27 |
코드 포매터(Formatter)와 린터(Linter) (0) | 2022.03.14 |
node-schedule을 사용한 작업 스케줄링 (0) | 2022.03.10 |
Node.js와 AWS RDS 연동 with Express, Prisma (0) | 2022.02.09 |