[typescript] 타입스크립트와 Cypress를 이용한 테스트 더블(mock, stub, spy) 활용

이번 포스트에서는 타입스크립트와 Cypress를 이용하여 테스트 더블(mock, stub, spy)을 활용하는 방법에 대해 알아보겠습니다. 테스트 더블은 실제 의존성을 대체하여 테스트를 더 효율적으로 만들어주는데, 타입스크립트와 Cypress를 함께 사용하여 테스트 더블을 구현하는 방법을 살펴보겠습니다.

목차

  1. 타입스크립트에서의 모의(mock)
  2. Cypress에서의 대역(stub, spy) 활용
  3. 결론

타입스크립트에서의 모의(mock)

모의(mock)는 테스트 중인 코드가 의존하는 모듈 또는 객체를 가짜로 대체하는 것을 말합니다. 타입스크립트에서는 Jest, Sinon.js 등의 라이브러리를 사용하여 모의를 구현할 수 있습니다. 아래는 Jest를 사용한 예시 코드입니다.

// Calculator.ts
export class Calculator {
  add(a: number, b: number): number {
    return a + b;
  }
}

// math.ts
import { Calculator } from './Calculator';

export function calculateTotal(calc: Calculator, a: number, b: number): number {
  return calc.add(a, b);
}
// math.spec.ts
import { Calculator } from './Calculator';
import { calculateTotal } from './math';

jest.mock('./Calculator', () => {
  return {
    Calculator: jest.fn().mockImplementation(() => {
      return {
        add: jest.fn().mockReturnValue(10),
      };
    }),
  };
});

describe('calculateTotal', () => {
  it('should return the sum of the numbers', () => {
    const calc = new Calculator();
    const total = calculateTotal(calc, 3, 7);
    expect(total).toBe(10);
  });
});

Cypress에서의 대역(stub, spy) 활용

Cypress는 End-to-End(E2E) 테스트를 위한 도구로, 대역(stub, spy)을 통해 외부 의존성을 대체하고 테스트 시나리오를 구현할 수 있습니다. 아래는 Cypress에서의 대역 활용 예시 코드입니다.

// example.spec.ts
import { fetchData } from './api';

describe('Data fetching', () => {
  it('fetches data using a stub', () => {
    const stub = cy.stub().resolves({ data: 'mocked data' });
    cy.wrap(fetchData(stub)).should('deep.equal', { data: 'mocked data' });
  });

  it('fetches data using a spy', () => {
    const spy = cy.spy(console, 'log').as('consoleLog');
    fetchData();
    cy.get('@consoleLog').should('be.calledWith', 'Data fetched');
  });
});

결론

이렇게 타입스크립트와 Cypress를 이용하여 테스트 더블(mock, stub, spy)을 활용하는 방법을 알아보았습니다. 테스트 더블을 통해 외부 의존성을 대체하여 테스트를 더 효율적으로 구현할 수 있습니다.

참고 문헌: