JavaScript
import { getMockReq, getMockRes } from '@jest-mock/express'
const req = getMockReq()
// an example GET request to retrieve an entity
const req = getMockReq({ params: { id: '123' } })
const { res, next, clearMockRes } = getMockRes()
return res.status(400).json({message: "드디어 탈출이다!"})
객체 내부에서 status(number) {} 은 status: function (number) {} 임, 그래서 status가 메서드가 아닌 프로퍼티로 인식된 것.
요렇게 하면 status: {status: number} 가 돼서 매개변수 number의 인수를 받아 값을 도출하는 메서드가 됨.
<멸망한 코드>
import express from "express";
import { getMockRes } from "@jest-mock/express"; //getMockReq도 있음
import { prisma } from "../src/utils/prisma/index.js";
const { res } = getMockRes({
status(number) {
return { status: number };
}, //getMockRes 는 res, next, clearMockRes가 있음
}); //clearMockRes는 모킹된 함수나 객체의 상태를 재설정함(초기화)
const app = express();
const router = express.Router();
const req = {
locals: { user: {} },
body: {},
}; // 가짜 요청 객체 생성
async function postWrite() {
req.locals.user = { userId: 1, nickname: "국밥의 왕" };
req.body = {
title: "국밥",
content: "멋진 국밥",
photo: "국밥1",
};
const { userId, nickname } = req.locals.user; //id = users 테이블의Id
const { title, content, photo } = req.body;
await prisma.posts.create({
data: {
userId: +userId,
title,
author: nickname,
content,
photos: {
create: { photo }, //{""} << 연결돼 있다면 여기에 필요한 프로퍼티 넣고 생성할 수 있음
},
},
});
return res.status(200);
}
test("국밥", async () => {
const response = await postWrite();
expect(response.status).toBe(200);
});
import express from "express";
import { prisma } from "../src/utils/prisma/index.js";
//getMockRes 는 res, next, clearMockRes가 있음
//clearMockRes는 모킹된 함수나 객체의 상태를 재설정함(초기화)
const app = express();
const router = express.Router();
const req = {
locals: { user: {} },
body: {},
}; // 가짜 요청 객체 생성
async function postWrite() {
req.locals.user = { userId: 1, nickname: "국밥의 왕" };
req.body = {
title: "국밥",
content: "멋진 국밥",
photo: "국밥1",
};
const { userId, nickname } = req.locals.user; //id = users 테이블의Id
const { title, content, photo } = req.body;
await prisma.posts.create({
data: {
userId: +userId,
title,
author: nickname,
content,
photos: {
create: { photo }, //{""} << 연결돼 있다면 여기에 필요한 프로퍼티 넣고 생성할 수 있음
},
},
});
return { status: 200 };
}
test("국밥", async () => {
const response = await postWrite();
expect(response.status).toBe(200);
});