Stratal API Reference
    Preparing search index...

    MSW-based fetch mock for declarative HTTP mocking in tests.

    Replaces the old Cloudflare fetchMock (undici MockAgent) with MSW's setupServer. Works in both Node.js and workerd test environments.

    import { createMockFetch } from '@stratal/testing'

    const mock = createMockFetch()

    beforeAll(() => mock.listen())
    afterEach(() => mock.reset())
    afterAll(() => mock.close())

    it('should mock external API', async () => {
    mock.mockJsonResponse('https://api.example.com/data', { success: true })

    const response = await fetch('https://api.example.com/data')
    const json = await response.json()

    expect(json.success).toBe(true)
    })
    Index

    Constructors

    • Parameters

      • handlers: RequestHandler<RequestHandlerDefaultInfo, any, any, RequestHandlerOptions>[] = []

      Returns MockFetch

    Methods

    • Mock an error response.

      Parameters

      • url: string

        Full URL to mock

      • status: number

        HTTP error status code

      • Optionalmessage: string

        Optional error message

      • options: MockErrorOptions = {}

        HTTP method, headers

      Returns void

      mock.mockError('https://api.example.com/fail', 401, 'Unauthorized')
      mock.mockError('https://api.example.com/fail', 500, 'Server Error', { method: 'POST' })
    • Mock a JSON response.

      Parameters

      Returns void

      mock.mockJsonResponse('https://api.example.com/users', { users: [] })
      mock.mockJsonResponse('https://api.example.com/users', { created: true }, { method: 'POST', status: 201 })
    • Add runtime handler(s) for a single test.

      Parameters

      • ...handlers: RequestHandler<RequestHandlerDefaultInfo, any, any, RequestHandlerOptions>[]

      Returns void