__________________________________________________
1-30 GET Method 통합 테스트
=> < 3.5 테스트 코드 06 >
3.5 테스트 코드 Goal : 테스트 코드란 무엇인지 이해하고 Jest를 이용해 단위 테스트 코드를 작성할 수 있다.
폴더 : kimminsoo -> sparta -> node_js -> learning -> third_step -> layered-architecture-pattern -> __test__
-> integration -> posts.integration.spec.js
처음으로 구현한 통합 테스트 코드는 GET /api/posts API.
해당하는 API는 PostsController의 getPosts Method가 호출되어 데이터 처리가 시작되게 되는데,
게시글 조회는 빈 값을 요청(Request) 받고, 조회된 Post 데이터들을 응답(Response)받고 있어.
——
GET /api/posts API의 검증 로직
- API를 호출하였을 때, 성공적으로 실행할 경우 200 Http Status Code를 반환한다.
- API의 Response는 아무런 데이터를 삽입하지 않은 상태이므로 { data: [] }의 구조를 가진다.
——
1.
GET /api/posts API의 검증 로직
——
test('GET /api/posts API (getPosts) Integration Test Success Case, Not Found Posts Data', async () => {
const response = await supertest(app).get(`/api/posts`); // API의 HTTP Method & URL
// 1. API status 코드가 200
expect(response.status).toEqual(200);
// 2. API 의 Response 데이터는 { data: [] }
expect(response.body).toEqual({data: []});
});
——
=> 실행 커멘드
——
npm run test:integration
——
__________________________________________________
1-31 POST Method 통합 테스트
=> < 3.5 테스트 코드 06 >
3.5 테스트 코드 Goal : 테스트 코드란 무엇인지 이해하고 Jest를 이용해 단위 테스트 코드를 작성할 수 있다.
폴더 : kimminsoo -> sparta -> node_js -> learning -> third_step -> layered-architecture-pattern -> __test__
-> integration -> posts.integration.spec.js
— POST Method 통합 테스트 (Integration Test) —
=>
2번째, 3번째 구현할 통합 테스트는 POST /api/posts API.
해당하는 API는 PostsController의 createPost Method.
——
// __tests__/integration/posts.integration.spec.js
const supertest = require('supertest');
const app = require('../../app.js');
const { sequelize } = require('../../models/index.js');
// 통합 테스트(Integration Test)를 진행하기에 앞서 Sequelize에 연결된 모든 테이블의 데이터를 삭제합니다.
// 단, NODE_ENV가 test 환경으로 설정되어있는 경우에만 데이터를 삭제합니다.
beforeAll(async () => {
if (process.env.NODE_ENV === 'test') await sequelize.sync();
else throw new Error('NODE_ENV가 test 환경으로 설정되어 있지 않습니다.');
});
describe('Layered Architecture Pattern, Posts Domain Integration Test', () => {
test('GET /api/posts API (getPosts) Integration Test Success Case, Not Found Posts Data', async () => {
const response = await supertest(app)
.get(`/api/posts`) // API의 HTTP Method & URL
.query({}) // Request Query String
.send({}); // Request Body
/** GET /api/posts API의 검증 로직 **/
// 1. API를 호출하였을 때, 성공적으로 실행할 경우 200 Http Status Code를 반환한다.
// 2. API의 Response는 아무런 데이터를 삽입하지 않은 상태이므로 { data: [] }의 형태를 가진다.
// 1. API를 호출하였을 때, 성공적으로 실행할 경우 200 Http Status Code를 반환한다.
expect(response.status).toEqual(200);
// 2. API의 Response는 아무런 데이터를 삽입하지 않은 상태이므로 { data: [] }의 형태를 가진다.
expect(response.body).toEqual({ data: [] });
});
test('POST /api/posts API (createPost) Integration Test Success Case', async () => {
// POST /api/posts API에서 사용되는 body 데이터입니다.
const createPostRequestBodyParams = {
nickname: 'Nickname_Success',
password: 'Password_Success',
title: 'Title_Success',
content: 'Content_Success',
};
const response = await supertest(app)
.post(`/api/posts`) // API의 HTTP Method & URL
.query({}) // Request Query String
.send(createPostRequestBodyParams); // Request Body
/** POST /api/posts API의 성공 케이스 검증 로직 **/
// 1. API를 호출하였을 때, 성공적으로 실행할 경우 201 Http Status Code를 반환한다.
// 2-1. API의 Response는 { data: createPostData }의 형식을 가집니다.
// 2-2. 여기서 createPostData는 { postId, nickname, title, content, createdAt, updatedAt }의 객체 형태를 가집니다.
// 1. API를 호출하였을 때, 성공적으로 실행할 경우 201 Http Status Code를 반환한다.
expect(response.status).toEqual(201);
// 2-1. API의 Response는 { data: createPostData }의 형식을 가집니다.
// 2-2. 여기서 createPostData는 { postId, nickname, title, content, createdAt, updatedAt }의 객체 형태를 가집니다.
expect(response.body).toMatchObject({
data: {
postId: 1,
nickname: createPostRequestBodyParams.nickname,
title: createPostRequestBodyParams.title,
content: createPostRequestBodyParams.content,
createdAt: expect.anything(), // 해당 Parameter가 존재하는지 확인합니다.
updatedAt: expect.anything(), // 해당 Parameter가 존재하는지 확인합니다.
},
});
});
// POST /api/posts API 에러 케이스 검증
test('POST /api/posts API (createPost) Integration Test Error Case, Invalid Params Error', async () => {
const createPostRequestBodyParams = {};
const response = await supertest(app)
.post(`/api/posts`)
.send(createPostRequestBodyParams);
// 1. API를 호출하였을 때, InvalidParamsError가 발생하여 400 Http Status Code를 반환
expect(response.status).toEqual(400);
// 2. API의 Response json(=response.body) 는 { errorMessage: "InvalidParamsError" }
expect(response.body).toMatchObject({ errorMessage: 'InvalidParamsError'});
});
test('GET /api/posts API (getPosts) Integration Test Success Case, is Exist Posts Data', async () => {
// TODO: 여기에 코드를 작성해야합니다.
});
});
afterAll(async () => {
// 통합 테스트가 완료되었을 경우 sequelize의 연결된 테이블들의 정보를 초기화합니다.
if (process.env.NODE_ENV === 'test') await sequelize.sync({ force: true });
else throw new Error('NODE_ENV가 test 환경으로 설정되어 있지 않습니다.');
});
——
=> 실행 커멘드
——
npm run test:integration
——
toMatchObject()은 언제 사용하는 건가.
=>
API를 호출한 후 반환된 데이터는 response.body 안에 **객체(Object)**의 형태로 존재하고 있어.
response.body 데이터 뿐만 아니라, Response Headers와 같이 다른 반환된 정보들을 검증할 때에도 사용된다고.
객체 내부에 있는 데이터들을 expect().toMatchObject({})문법을 이용해 데이터를 검증할 수 있어.
expect.anythind()은 어떤 역할을 하는 것인가.
=>
null, undefined과 일치하는지 검증할 때 사용.
특정 시간을 기준으로 만들어지는 createdAt, updatedAt과 같이
객체의 특정 Parameter가 존재하는지에 대한 여부를 검증하기 위해 사용.
참조 : https://jestjs.io/docs/expect#expectanything
이것으로 post api 의 성공 사례, 실패 사례를 모두 검증.
'내일배움캠프_개발일지 > Node.js 기초' 카테고리의 다른 글
Node.js 심화 socket -1- (0) | 2023.01.12 |
---|---|
Node.js 심화 - 14 (0) | 2023.01.11 |
Node.js 심화 - 12 (1) | 2023.01.08 |
Node.js 심화 - 11 (0) | 2023.01.08 |
Node.js 심화 - 10 (0) | 2023.01.06 |