Angular 테스트(Test) 하기

2018. 4. 11. 22:00

Angular의 테스트에 대해 보고자 합니다.

여지껏 테스트는 안해왔는데요.

(테스트할 코드가 많지 않았기도했지만...)


Angular는 Jasmine이라는 테스트 프레임웍을 사용합니다.

Jasmine은 테스트를 이해하기 쉽게 정리하는 것을 돕습니다.


아래 예제를 참고해보도록 하죠.

describe('BudgetComponent', () => {
  ...
  it('should create', () => {
    expect(component).toBeTruthy();
  });
  ...
}


테스트 코드의 일부를 가져와봤습니다.

it은 무엇이 테스트 되는지를 보여줍니다.

describe는 여러개의 it을 묶어서 설명합니다.


또한 Jasmine은 테스트를 편리하게 하기 위한 API를 제공하죠.

예를들어 아래와 같은 메서드들이 있습니다.

expect().nothing();
expect(thing).toBe(expected);
expect(result).toBeDefined();
expect(result).toBeGreaterThan(3);
expect(result).toBeLessThan(0);
expect(thing).toBeNaN();
expect(result).toBeNull();
expect(thing).toBeTruthy();
expect(array).toContain(anElement);
expect(string).toContain(substring);
expect(bigObject).toEqual({"foo": ['bar', 'baz']});
...


메서드의 이름만 봐도 어떤 걸 테스트하는지 이해가 됩니다.

더 많은 메서드들은 아래 출처에서 참고하시면 되구요.


Angular 테스트를 수행하려면 아래와 같은 명령어 하나면 됩니다.

ng test


위와 같이 실행하면 브라우저에 아래와 같은 화면이 뜹니다.


Angular Test 실행화면



Karma라는 툴이 실행됨을 알 수 있는데요.

Jasmine 테스트를 브라우저로 쉽게 수행하는 걸 돕습니다.

Jasmine 테스트를 위해 html을 작성해야하는데요.

Karma가 대신하도록 Angular에 이미 설정이 되어있습니다.


그럼 실제 테스트 코드를 보도록 하죠.

Budget Component를 테스트하는 코드입니다.

budget.component.spec.ts 파일이에요.

테스트 코드는 spec 파일에 작성하게 됩니다.

import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { MatInputModule } from '@angular/material/input';
import { MatTableModule } from '@angular/material/table';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { BudgetComponent } from './budget.component';

describe('BudgetComponent', () => {
  let component: BudgetComponent;
  let fixture: ComponentFixture;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ BudgetComponent ],
      imports: [ MatInputModule, MatTableModule, BrowserAnimationsModule ]
    })
    .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(BudgetComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });

  it('should have budget value', () => {
    const budgetComponent: HTMLElement = fixture.nativeElement;
    let titleElement = budgetComponent.querySelector(".budget-total");
    expect(titleElement.textContent).toEqual("Today's Budget: ₩ 20000");
  })
});


먼저 BudgetComponent가 사용하는 모듈들이 import되어야 합니다.

그리고 it이 수행되기 전 필수 작업들이 beforeEach에서 수행되죠.

컴포넌트를 컴파일하고 화면을 그리는 작업입니다.


'should create'라는 테스트는 기본으로 생성됩니다.

component가 생성 되는지를 테스트하는 것이지요.

빠진 모듈이 있으면 should create부터 실패합니다.


저는 budget value가 셋팅이 되는지를 테스트했습니다.

fixture.nativeElement로부터 화면을 가져올 수 있어요.

budget-total 클래스를 가진 h3 요소의 값을 검사했습니다.

20000으로 설정된 값이 표출되고 있는지를요.

간단한 테스트죠.


더 복잡하고 다양한 테스트 스킬이 존재합니다.

경험해보면서 공유할 가치가 있는 것들은 공유할게요.


코드가 변하면서 테스트도 변해야합니다.

TDD(Test Driven Development)가 한창 화두일 때가 있었죠.

테스트를 먼저 작성하고 코딩을 하는 방식인데요.

저는 적절히 섞어서 작업해나갈 예정입니다.


소스주소: https://github.com/jsrho1023/account-book


출처:

https://angular.io/guide/testing

https://jasmine.github.io/tutorials/your_first_suite

'IT Tech > Angular' 카테고리의 다른 글

Angular Service 만들기  (2) 2018.05.13
Angular Domain Model  (0) 2018.04.24
Angular Material Table  (0) 2018.04.02
Angular Material Icon  (0) 2018.03.18
Angular Material Header Toolbar  (0) 2018.03.11

TechTrip IT Tech/Angular