[Nest.js] Test

zunzero·2022년 11월 1일
0

Node.js

목록 보기
4/4

Jest

testing framework로 Jest가 기본 제공된다.
mocking과 spying을 가능하게 하고, test-runner로써의 기능을 제공한다.

built-in Test class

내장 Test 클래스가 존재한다.
Test 클래스는 전에 Nest runtime을 mock하는 application execution context를 제공한다.
mocking과 overriding을 포함해 클래스 인스턴스를 관리하기 편하게 하는 hook도 제공한다.

Test 클래스는 createTestingModule() 메서드를 갖고 있는데, 이는 module metadata 객체를 argument로 취한다.
@Module() decorator에 보내는 객체와 같은 객체이다.
해당 메서드는 TestingModule 인스턴스를 반환한다.

unit test에서, 가장 중요한 것은 compile() 메서드이다.
이 메서드는 의존성들을 포함해 module을 bootstrap하고 테스트가 준비된 module을 반환한다.
(main.ts에서 NestFactory.create() 메서드를 활용해서 어플리케이션을 bootstrap하는 것과 비슷하다.)

import { Test } from '@nestjs/testing';
import { CatsController } from './cats.controller';
import { CatsService } from './cats.service';

describe('CatsController', () => {
  let catsController: CatsController;
  let catsService: CatsService;
  
  beforeEach(async () => {
    const moduleRef = await Test.createTestingModule({
      controllers: [CatsController],
      providers: [CatsService],
    }).compile();
    
    catsService = moduleRef.get<CarseService>(CatsService);
    catsController = moduleRef.get<CatsController>(CatsController);
  });
  
  describe('findAll', () => {
    it('should return an array of cats', async () => {
      const result = ['test'];
      jest.spyOn(catsService, 'findAll').mockImplementation(() => result);
      
      expect(await catsController.findAll()).toBe(result);
    });
  });
});

TestingModule은 module reference class를 상속받는데, 이는 동적으로 provider를 resolve 할 수 있도록 한다.

const moduleRef = await Test.createTestingModule({
  controllers: [CatsController],
  providers: [CatsService],
}).compile();

catsService = await moduleRef.resolve(CatsService);

resolve는 그만의 DI container sub-tree로부터 provider의 unique instance를 반환한다.
각각의 sub-tree는 unique context identifier를 가지고 있다.
따라서 만약 해당 메서드를 두 번 이상 호출하여 인스턴스 reference를 비교하면, 동일하지 않음을 확인할 수 있을 것이다.

공식문서를 정리한 내용은 여기까지다.
더 많은 내용이 있지만 현재 시점에서 공부할 내용은 아닌 것 같다.

현재 회사에서 작성된 테스트 코드를 뜯어보면서, 회사의 입맛에 맞추어 적응하는 쪽으로 우선 가야겠다.

Nestjs와 Prisma를 사용 중이니, 이에 맞는 테스트 코드에 적응해야겠다.

화이띵 ~

profile
나만 읽을 수 있는 블로그

0개의 댓글