Given-When-Then은 주로 BDD(Behavior-Driven Development)에서 사용되는 테스트 시나리오 작성 패턴으로 테스트 의도를 쉽게 공유하고 이해할 수 있게 해줍니다.
- Given (상황 설정):
- 테스트의 시작 상태 또는 전제 조건을 설정합니다.
- 애플리케이션이 어떤 상태에 있는지를 설명합니다.
- When (행동):
- 테스트하려는 특정 행동이나 이벤트를 정의합니다.
- 애플리케이션이 처리해야 할 동작을 설명합니다.
- Then (결과):
- 행동이 발생한 후 기대하는 결과를 정의합니다.
- 애플리케이션이 어떻게 반응해야 하는지를 설명합니다.
- 예시
- (Given) 사용자가 로그인하지 않은 상태에서 시작한다.
- (When) 사용자가 로그인 버튼을 클릭한다.
- (Then) 사용자가 대시보드 페이지로 이동한다.
e2e 테스트 예시
import { Test, TestingModule } from '@nestjs/testing';
import { INestApplication } from '@nestjs/common';
import * as request from 'supertest';
import { AppModule } from './../src/app.module';
describe('AuthController (e2e)', () => {
let app: INestApplication;
beforeAll(async () => {
const moduleFixture: TestingModule = await Test.createTestingModule({
imports: [AppModule],
}).compile();
app = moduleFixture.createNestApplication();
await app.init();
});
afterAll(async () => {
await app.close();
});
it('등록되지 않은 사용자가, 로그인을 요청을 시도한다. 그러면 401 Unauthorized 상태 코드를 받아야 한다', async () => {
// Given: 사용자가 등록되지 않은 상태
const loginPayload = {
email: 'nonexistent@example.com',
password: 'invalidpassword',
};
// When: 사용자가 로그인 요청을 시도한다
const response = await request(app.getHttpServer())
.post('/auth/login')
.send(loginPayload);
// Then: 401 Unauthorized 상태 코드를 받아야 한다
expect(response.status).toBe(401);
});
});
'TDD > jest' 카테고리의 다른 글
[ jest ] Reflect.getMetadata(metadataKey, target) - 설정된 메타데이터 확인하는 메서드 (0) | 2024.12.02 |
---|---|
[ jest ] mockResolvedValue와 mockReturnValue의 차이 (0) | 2024.12.02 |
[ jest ] toBe vs toEqual vs toStrictEqual 차이점 (0) | 2024.12.01 |
[ jest ] 에러 처리를 위한 단위 테스트 작성 (Create) (0) | 2024.11.14 |
[ jest ] express + jest 기본 설정 (1) | 2024.11.14 |