반응형
단위테스트에서 http 객체 (request, response)를 얻으려면 node-mocks-http를 이용하면 된다.
npm install node-mocks-http
let req = httpMocks.createRequest();
let res = httpMocks.createResponse();
이전 포스팅에(2023.02.23 - [Node.js/TDD] - 단위 테스트 create) 이어서 createProduct에 req.body를 넣어주기 위해서
node-mocks-http를 이용해 req와 res를 선언하고
req.body에 넣어줄 json 데이터 파일을 생성해서 req.body에 할당후,
productModel.create 메서드가 newProduct와 함께 호출되는지 체크해주었다.
const productController = require("../../controller/products");
const productModel = require("../../models/Product");
const httpMocks = require("node-mocks-http");
const newProduct = require("../data/new-product");
productModel.create = jest.fn();
describe("Product Controller Create", () => {
it("should have a createProduct function", () => {
expect(typeof productController.createProduct).toBe("function");
});
it("should call ProductModel.create", () => {
let req = httpMocks.createRequest();
let res = httpMocks.createResponse();
let next = null;
req.body = newProduct;
productController.createProduct(req, res, next); // createProduct 가 호출 될 때
expect(productModel.create).toBeCalledWith(newProduct); // 이 메소드가 실행되는지 체크
});
});
beforeEach
여러 개의 테스트에 공통된 코드가 있다면 beforeEach 안에 넣어서 반복을 줄여줄 수 있다.
위 코드에 적용하면 다음과 같이 여러 테스트 코드에서 사용 가능하다.
const productController = require("../../controller/products");
const productModel = require("../../models/Product");
const httpMocks = require("node-mocks-http");
const newProduct = require("../data/new-product");
productModel.create = jest.fn();
let req, res, next;
beforeEach(() => {
req = httpMocks.createRequest();
res = httpMocks.createResponse();
next = null;
});
describe("Product Controller Create", () => {
beforeEach(() => {
req.body = newProduct;
});
it("should have a createProduct function", () => {
expect(typeof productController.createProduct).toBe("function");
});
it("should call ProductModel.create", () => {
productController.createProduct(req, res, next); // createProduct 가 호출 될 때
expect(productModel.create).toBeCalledWith(newProduct); // 이 메소드가 실행되는지 체크
});
});
반응형
'Node.js > TDD' 카테고리의 다른 글
통합 테스트(Intergration Test) (0) | 2023.03.01 |
---|---|
단위 테스트 create (0) | 2023.02.23 |
TDD ( Test Driven Development ) (0) | 2023.02.21 |