Vitest/Jest Fake Timers로 시간 제어

describe('time-dependent tests', () => {
  beforeEach(() => {
    vi.useFakeTimers() // jest.useFakeTimers()
  })

  afterEach(() => {
    vi.useRealTimers() // jest.useRealTimers()
  })

  it('특정 시간에 동작 확인', () => {
    vi.setSystemTime(new Date(2000, 1, 1, 13)) // 13시 설정
    expect(purchase()).toEqual({ message: 'Success' })
  })

  it('영업시간 외 동작', () => {
    vi.setSystemTime(new Date(2000, 1, 1, 19)) // 19시 설정
    expect(purchase()).toEqual({ message: 'Error' })
  })
})

@sinonjs/fake-timers 기반. Date, setTimeout 등 모킹.1


Footnotes

  1. vi - Vitest: “The implementation is based internally on @sinonjs/fake-timers.” / The Jest Object: “Fake timers implementation is backed by @sinonjs/fake-timers.” ↩

#347

https://www.emgoto.com/jest-partial-match/

objectContaining·arrayContaining 은 toEqual·toHaveBeenCalledWith 안에 중첩해서 쓴다.1

test('호출 인자 부분 매칭', () => {
  const mockFunction = jest.fn()

  mockFunction({ id: 1, name: 'Alice', tags: ['developer', 'designer'] })

  expect(mockFunction).toHaveBeenCalledWith(
    expect.objectContaining({
      name: 'Alice',
      tags: expect.arrayContaining(['designer']),
    })
  )
})

test('배열 안 객체 부분 매칭', () => {
  const receivedArray = [
    { id: 1, name: 'Alice' },
    { id: 2, name: 'Bob' },
  ]

  expect(receivedArray).toEqual(
    expect.arrayContaining([
      expect.objectContaining({ name: 'Alice' }),
      expect.objectContaining({ id: 2 }),
    ])
  )
})

Footnotes

  1. Expect - Jest: “You can use it instead of a literal value:” … “in toEqual or toHaveBeenCalledWith” / “to match a property in objectContaining or toMatchObject” ↩

#374

Jest setupFiles vs setupFilesAfterEnv - 실행 시점이 다르다.

  • setupFiles: 테스트 프레임워크 설치 전. expect·beforeEach 가 아직 없다(jest 객체는 있다). 환경 변수, 폴리필용.
  • setupFilesAfterEnv: 테스트 프레임워크 설치 후. jest.setTimeout(), 커스텀 matcher, 전역 beforeEach용.

process.env는 setupFiles에 둔다(용도 구분). 다만 둘 다 테스트 코드보다 먼저 돌아서, setupFilesAfterEnv에서 설정해도 테스트 파일이 import 하는 모듈에는 보인다.1

// jest.config.js
{ setupFiles: ['./jest.env.js'], setupFilesAfterEnv: ['./jest.setup.js'] }

// jest.env.js - 환경 변수
process.env.API_URL = 'http://test-api.example.com'

// jest.setup.js - Jest API 활용
import '@testing-library/jest-dom'
beforeEach(() => { jest.clearAllMocks() })

Footnotes

  1. Configuring Jest — setupFilesAfterEnv: “Since setupFiles executes before the test framework is installed in the environment, this script file presents you the opportunity of running some code immediately after the test framework has been installed in the environment but before the test code itself.” ↩

#505