빠른 참조

Jasmine BDD 테스트 치트시트

Jasmine 테스트 프레임워크 빠른 참조 가이드: describe/it 구조, 매처(Matchers), 스파이(Spies), 비동기 테스트 및 훅을 정리합니다.

· 게시일

Jasmine은 외부 DOM 종속성 없이 JavaScript 코드를 테스트하기 위한 행위 주도 개발(BDD) 프레임워크입니다.

테스트 구조 및 BDD 문법

describe('Calculator', () => {
  let calc;

  beforeEach(() => {
    calc = new Calculator();
  });

  afterEach(() => {
    calc.cleanup();
  });

  it('should add two numbers correctly', () => {
    expect(calc.add(2, 3)).toBe(5);
  });

  xit('temporarily skipped test', () => {
    // pending
  });
});

매처 (Matchers)

expect(val).toBe(true);              // Strict equality (===)
expect(val).toEqual({ a: 1 });       // Deep object equality
expect(val).toMatch(/regex/);        // Regular expression match
expect(val).toBeDefined();           // Not undefined
expect(val).toBeUndefined();         // Is undefined
expect(val).toBeNull();              // Strict null
expect(val).toBeTruthy();            // Truthy coercion
expect(val).toBeFalsy();             // Falsy coercion
expect(arr).toContain('item');       // Array or string inclusion
expect(val).toBeLessThan(10);        // Numeric comparisons
expect(val).toBeGreaterThan(5);
expect(fn).toThrow();                // Exception thrown
expect(fn).toThrowError(TypeError);

.not을 사용하여 모든 매처를 반전할 수 있습니다:

expect(val).not.toBeNull();

스파이(Spies) 및 모의 함수

// Spy on an existing object method
spyOn(service, 'fetchData').and.returnValue(Promise.resolve([1, 2]));

service.fetchData('users');

expect(service.fetchData).toHaveBeenCalled();
expect(service.fetchData).toHaveBeenCalledWith('users');
expect(service.fetchData.calls.count()).toBe(1);

// Create standalone anonymous spy
const callback = jasmine.createSpy('myCallback');
callback('payload');
expect(callback).toHaveBeenCalledWith('payload');

비동기 테스트

it('fetches async data', async () => {
  const result = await fetchItems();
  expect(result.length).toBeGreaterThan(0);
});

참고 자료

관련 주제