210511 Node.js TDD Practice 다섯번째 이야기 - 통합 테스트 (Integration Test) 코드 작성

Nodejs Mocking Http Request

통합 테스트(Integration Test)

모듈을 통합하는 단계에서 수행하는 테스트로, 단위 테스트를 통해서 모듈들이 모두 잘 작동하는 것을 확인한 뒤에 모듈들을 서로 연동하여 테스트를 수행하는 것을 말한다.

Supertest

단위 테스트에서 jest 모듈을 사용해서 테스트를 했다면, 통합 테스트는 supertest라는 모듈을 이용해서 구현을 한다.

단위 테스트에서는 MongoDB 부분은 문제가 없다는 가정하에 mock 함수로 처리를 했는데 통합 테스트에서는 supertest를 사용해서 실제로 요청을 보내서 테스트를 진행한다.

통합 테스트 코드 작성

통합 테스트 코드는 실제 작성한 코드의 로직을 기반으로 작성한다.

예를들어 아래와 같이 MongoDB에 req.body를 통해 넘겨받은 데이터를 새로 추가하고 추가된 데이터를 별도의 변수에 담아 response의 status code가 201인 경우에 json 데이터로 함께 전달하고 있다.

1
2
3
4
5
6
7
8
9
exports.createProduct = async (req, res, next) => {
try {
const newProduct = await productModel.create(req.body);
console.log('createProduct', newProduct);
res.status(201).json(newProduct);
} catch (error) {
next(error);
}
};

위의 코드를 통합 테스트 코드로 작성을 하면, 아래와 같이 통합테스트 코드를 구현할 수 있다.

1
2
3
4
5
6
7
8
9
10
11
12
13
const request = require('supertest');
const app = require('../../server');
const newProduct = require('../data/new-data.json');

test('POST /api/products', async () => {
// 실제 코드와 같이 요청을 보내고 함께 보낸 데이터를 response 변수에 담는다.
const response = await request(app).post('/api/products').send(newProduct);
// 위의 response 객체의 상태코드를 확인
expect(response.statusCode).toBe(201);
// response의 body(json) 데이터를 확인을 한다.
expect(response.body.name).toBe(newProduct.name);
expect(response.body.description).toBe(newProduct.description);
});
Read more