Skip to content

Feature Request: support network mocking #9924

@sheremet-va

Description

@sheremet-va

Clear and concise description of the problem

We want to support a unified network mocking mechanism in Vitest: both in Node.js and in the browser. This is a pain point that a lot of projects face, having to resort to third-party solutions. We even have a documentation page about network mocking.

Suggested solution

MSW is an industry standard in network mocking. If we ever have this feature, we should follow the same API. I want to propose these drafts based on MSW implementation:

// having all utilities in `vi`
import { vi } from 'vitest'

const networkMocker = vi.setupNetworkMocker(
  vi.http.get('/response', () => new Response(null, { statusCode: 404 }),
)
await networkMocker.start()
// having all utilities in `vitest/network`
import { http, setupNetworkMocker } from 'vitest/network'

const networkMocker = setupNetworkMocker(
  http.get('/response', () => new Response(null, { statusCode: 404 }),
)
await networkMocker.start()
// split utilities between different places
import { http } from 'vitest/mock-http'

 // if we every support graphql, it should not be exposed form the same entry point for types support
import { graphql } from 'vitest/mock-graphql'
import { vi } from 'vitest'

const github = graphql.link('https://api.github.com/graphql')

const networkMocker = vi.setupNetworkMocker(
  http.get('/response', () => new Response(null, { statusCode: 404 }),
  github.query('GetUser', oneResolver),
)
await networkMocker.start()

The naming is not final as is the API.

As a rule, we want MSW's handlers to be supported out of the box, so this is also valid:

import { http } from 'msw'
import { vi } from 'vitest'

const server = vi.setupNetworkMocker(
  http.get('/response', () => new Response(null, { statusCode: 404 }),
)

Alternative

No response

Additional context

MSW has @mswjs/interceptors package that we can use.

Having network capabilities built-in, we can also expose config option like networkMockingReset that would reset handlers after every test (enabled by default).

We could also keep the mocker in memory and enable/disable it automatically without the need to specify beforeAll/afterAll hooks.

Validations

Metadata

Metadata

Assignees

No one assigned

    Labels

    p2-nice-to-haveNot breaking anything but nice to have (priority)

    Projects

    Status

    Approved

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions