1. afterEach - 매 테스트가 끝날 때마다 실행
언제 쓰나요?
- 각 테스트 케이스가 서로 영향을 주지 않도록 격리시킬 때
- 메모리 누수 방지 (특히 컴포넌트 테스트)
- spy, mock 초기화
실전 예제
describe('MyComponent', () => {
let component: MyComponent;
let fixture: ComponentFixture<MyComponent>;
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [ MyComponent ]
});
fixture = TestBed.createComponent(MyComponent);
component = fixture.componentInstance;
});
// 핵심! 매 테스트 후 정리
afterEach(() => {
fixture.destroy(); // ChangeDetection 오류 방지
// localStorage.clear();
// jasmine.clock().uninstall();
});
it('should create', () => {
expect(component).toBeTruthy();
});
it('should change title', () => {
component.title = 'new';
fixture.detectChanges();
expect(component.title).toBe('new');
});
});
자주 쓰이는 afterEach 정리 작업
| 작업 내용 |
이유 |
| fixture.destroy() |
메모리 누수 & ChangeDetection 오류 방지 |
| httpMock.verify() |
남아있는 HTTP 요청 없도록 확인 |
| spy.and.callThrough() 복원 |
다음 테스트에 영향 안 주기 위해 |
| localStorage.clear() |
저장소 오염 방지 |
2. afterAll - 모든 테스트가 끝난 후 딱 한 번만 실행
언제 쓰나요?
- 전체 테스트 스위트가 끝난 후 마무리 작업이 필요할 때
- 서버 모킹 종료, 로그 출력 등
실전 예제
describe('UserService HTTP 테스트', () => {
let httpMock: HttpTestingController;
let service: UserService;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [HttpClientTestingModule],
providers: [UserService]
});
service = TestBed.inject(UserService);
httpMock = TestBed.inject(HttpTestingController);
});
afterEach(() => {
// 각 테스트마다 요청이 모두 처리됐는지 확인
httpMock.verify();
});
// 모든 테스트가 끝난 후 한 번만!
afterAll(() => {
console.log('UserService 전체 테스트 완료!');
// 전체 mock 서버 종료 등의 작업 가능
});
it('should get users', () => { /* ... */ });
it('should post user', () => { /* ... */ });
});
한눈에 비교 정리
| 훅 |
실행 시점 |
실행 횟수 |
주요 용도 |
| afterEach |
각 it()이 끝날 때마다 |
테스트 수만큼 |
개별 테스트 격리, fixture 정리, spy 초기화 |
| afterAll |
describe 전체가 끝난 후 |
딱 1번 |
전체 자원 해제, 최종 로그, httpMock.verify() 대체 가능 |
Tip: HttpClientTestingModule을 쓰면 보통 afterEach에서 httpMock.verify()를 호출합니다. afterAll에서는 거의 안 쓰지만, 전체 테스트 종료 시점에 뭔가 특별한 작업이 필요할 때만 사용하세요!
결론
- 99%의 경우 → afterEach로 충분!
- fixture.destroy()와 httpMock.verify()는 잊지 말고 넣자!
- afterAll은 정말 “전체가 끝난 후 한 번만” 해야 할 일이 있을 때만 쓰세요.