JEST#1-3. @jest-mock/express

깡통·2024년 2월 7일
0
  • 오늘의 교훈, es6는 틀렸다. 다음 과제부턴 require만 쓴다 진짜.
  • es6 진짜 외부 모듈이랑 호환 너무 안돼;;;;
  • @jest-mock/express를 쓰니까 끔찍했던 jest.mock('express')를 쓰지 않고도 res 객체를 정의해서 사용할 수 있게 됐다!

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: "드디어 탈출이다!"})
  • 그런데 일단 테스트는 돌아가는데, 테스트 fail이 되면서 사유가 mockConstructor 함수가 반환됐기 때문이라고 한다. getMockRes() 함수는 생성자 함수인 것 같다.

객체 내부에서 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);
});
  • 끝끝내 성공은 했는데, 결국 express 모듈을 사용하진 못했다. 아쉽다 정말
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);
});
profile
코딩하러 온 사람입니다.

0개의 댓글