컨트롤러 수준에서 DB service 로직을 신뢰하고 테스트를 진행하기로 했다.
목업데이터 대신 TestDB에 연결하여 테스트를 진행했다.
Jest 실행 시, NODE_ENV=test로 자동설정된다.
// ~.controller.spec.ts
import { INestApplication } from '@nestjs/common';
import request from 'supertest';
import { Test, TestingModule } from '@nestjs/testing';
import { AppController } from '../app.controller';
import { AppModule } from '../app.module';
import { AppService } from '../app.service';
describe('HomeController', () => {
let app: INestApplication;
let accessToken: string;
beforeAll(async () => {
const module: TestingModule = await Test.createTestingModule({
imports: [
AppModule
],
controllers: [AppController],
providers: [AppService],
}).compile();
await module.init();
app = module.createNestApplication();
await app.init();
});
it('Should be failed Signin, Because invalid password', async () => {
const res = await request(app.getHttpServer())
.post('/sign/email/in')
.set('Accept', 'application/json')
.type('application/json')
.send({
email: '1@1.com',
password: '123',
}).then().catch()
expect(res.body.success).toEqual(false);
});
afterAll(() => {
app.close();
});
}
supertest를 사용한 response는 해당 라우터의 함수 결과를 리턴한다.
에러를 리턴하면 에러코드와 에러메세지를 확인하면 될듯하다.
헤더에 추가하고싶은 항목들이 있다면 .set()에 추가하면 된다.
// Bearer token example
const res = await request(app.getHttpServer())
.get('/user')
.set('Accept', 'application/json')
.set('Authorization', `Bearer ${accessToken}`)
.type('application/json')
.then();
참고)
https://www.npmjs.com/package/supertest
supertest
SuperAgent driven library for testing HTTP servers. Latest version: 6.3.3, last published: a month ago. Start using supertest in your project by running `npm i supertest`. There are 1096 other projects in the npm registry using supertest.
www.npmjs.com
'Server > NodeJS & NestJS' 카테고리의 다른 글
Node) google news rss로 읽어오기 (0) | 2023.03.07 |
---|---|
NestJS) ChatGPT API 사용후기 (0) | 2023.02.01 |
NestJS) Jest TDD Setting (0) | 2023.01.10 |
NestJS) Winston logger로 console.log 사용하기 (0) | 2022.12.20 |
NestJS) Create APIdocs(openAPI) with swagger (0) | 2022.11.03 |