Prisma Integration testing

00_8_3·2022년 7월 28일
0

Migration To Prisma

목록 보기
7/11

Prisma Integration testing

분리되어 있는 각 파트가 어떻게 동작하는지 확인하기 위한 방법으로 통합 테스트를 적용.텍스트

각 테스트마다 db의 내용들을 초기화 하기위해 사용.

const transactions: PrismaPromise<any>[] = []
transactions.push(prisma.$executeRaw`SET FOREIGN_KEY_CHECKS = 0;`)

const tablenames = await prisma.$queryRaw<
  Array<{ TABLE_NAME: string }>
>`SELECT TABLE_NAME from information_schema.TABLES WHERE TABLE_SCHEMA = 'tests';`// tests자리에 db이름

for (const { TABLE_NAME } of tablenames) {
  if (TABLE_NAME !== '_prisma_migrations') {
    try {
      transactions.push(prisma.$executeRawUnsafe(`TRUNCATE ${TABLE_NAME};`))
    } catch (error) {
      console.log({ error })
    }
  }
}

transactions.push(prisma.$executeRaw`SET FOREIGN_KEY_CHECKS = 1;`)

try {
  await prisma.$transaction(transactions)
} catch (error) {
  console.log({ error })
}

with docker container

version: "3.7"

services:
  mysql:
    image: mysql:5.7
    container_name: prisma
    volumes:
      - prisma:/var/lib/mysql
    environment: 
      MYSQL_ROOT_PASSWORD: test
      MYSQL_DATABASE: prisma
      TZ: Asia/Seoul
    ports:
      - '3306:3306'
    command:
      - --character-set-server=utf8mb4
      - --collation-server=utf8mb4_unicode_ci
    restart: unless-stopped

volumes:
  prisma:

이슈

Integration testingunit testing을 따로 실행 하는 경우 문제가 없지만
jest config의 setupFilesAfterEnv 옵션에 singleton.ts 넣어주면

unit testing을 위한 mock이 주입되기 때문에
Integration testing할 경우 db에 접근을 못해 실패하게 된다.

이것을 해결 하기위해 생각 2가지는

  • 통합이냐 유닛 테스트냐에 따른 jest config setupFilesAfterEnv 분기처리로 singleton.ts 주입
  • singleton.ts 내용을 모든 유닛 테스팅 코드에 직접 주입.

첫 번째 해결방법을 사용 하고 싶었으나 관련 jest 옵션을 찾지 못했다.

두 번째 해결방법도 깔끔 하지는 않은 것이 외부모듈(singleton.ts)를 각 테스트 코드에 호출하여 사용 하려 하니 jest-mock-extended의 mock.mockReset 오류가 발생하여 각 테스트 코드마다 중복코드를 작성해야만 했다.

출처

https://www.prisma.io/docs/guides/testing/integration-testing

0개의 댓글