msw

  • Version 2.14.6
  • Published
  • 5.59 MB
  • 18 dependencies
  • MIT license

Install

npm i msw
yarn add msw
pnpm add msw

Overview

Seamless REST/GraphQL API mocking library for browser and Node.js.

Index

Variables

Functions

Classes

Interfaces

Enums

Type Aliases

Variables

variable graphql

const graphql: {
query: GraphQLRequestHandler;
mutation: GraphQLRequestHandler;
operation: GraphQLOperationHandler;
link(url: Path): GraphQLLinkHandlers;
};
  • A namespace to intercept and mock GraphQL operations

    Example 1

    graphql.query('GetUser', resolver) graphql.mutation('DeletePost', resolver)

    See Also

variable http

const http: {
all: HttpRequestHandler;
head: HttpRequestHandler;
get: HttpRequestHandler;
post: HttpRequestHandler;
put: HttpRequestHandler;
delete: HttpRequestHandler;
patch: HttpRequestHandler;
options: HttpRequestHandler;
};
  • A namespace to intercept and mock HTTP requests.

    Example 1

    http.get('/user', resolver) http.post('/post/:id', resolver)

    See Also

variable sse

const sse: ServerSentEventRequestHandler;
  • Intercept Server-Sent Events (SSE).

    Example 1

    sse('http://localhost:4321', ({ client }) => { client.send({ data: 'hello world' }) })

    See Also

variable ws

const ws: WebSocketNamespace;
  • A namespace to intercept and mock WebSocket connections.

    Example 1

    const chat = ws.link('wss://chat.example.com')

    See Also

Functions

function bypass

bypass: (input: BypassRequestInput, init?: RequestInit) => Request;
  • Creates a Request instance that will always be ignored by MSW.

    Example 1

    import { bypass } from 'msw'

    fetch(bypass('/resource')) fetch(bypass(new URL('/resource', 'https://example.com))) fetch(bypass(new Request('https://example.com/resource')))

    See Also

function cleanUrl

cleanUrl: (path: string) => string;
  • Removes search parameters and the fragment from a given URL string.

function delay

delay: (durationOrMode?: DelayMode | number) => Promise<void>;
  • Delays the response by the given duration (ms).

    Example 1

    await delay() // emulate realistic server response time await delay(1200) // delay response by 1200ms await delay('infinite') // delay response infinitely

    See Also

function getResponse

getResponse: (
handlers: Array<RequestHandler>,
request: Request,
resolutionContext?: ResponseResolutionContext
) => Promise<Response | undefined>;
  • Finds a response for the given request instance in the array of request handlers.

    Parameter handlers

    The array of request handlers.

    Parameter request

    The Request instance.

    Parameter resolutionContext

    Request resolution options.

    Returns

    {Response} A mocked response, if any.

function handleRequest

handleRequest: (
request: Request,
requestId: string,
handlers: Array<RequestHandler>,
options: RequiredDeep<SharedOptions>,
emitter: Emitter<LifeCycleEventsMap>,
handleRequestOptions?: HandleRequestOptions
) => Promise<Response | undefined>;

    function isCommonAssetRequest

    isCommonAssetRequest: (request: Request) => boolean;
    • Determines if the given request is a static asset request. Useful when deciding which unhandled requests to ignore. Despite being ignored, you can still intercept and mock static assets by creating request handlers for them.

      Example 1

      import { isCommonAssetRequest } from 'msw'

      await worker.start({ onUnhandledRequest(request, print) { if (!isCommonAssetRequest(request)) { print.warning() } } })

    function matchRequestUrl

    matchRequestUrl: (url: URL, path: Path, baseUrl?: string) => Match;
    • Returns the result of matching given request URL against a mask.

    function onUnhandledRequest

    onUnhandledRequest: (
    request: Request,
    strategy?: UnhandledRequestStrategy
    ) => Promise<void>;

      function passthrough

      passthrough: () => HttpResponse<any>;
      • Performs the intercepted request as-is.

        This stops request handler lookup so no other handlers can affect this request past this point. Unlike bypass(), this will not trigger an additional request.

        Example 1

        http.get('/resource', () => { return passthrough() })

        See Also

      Classes

      class GraphQLHandler

      class GraphQLHandler extends RequestHandler<
      GraphQLHandlerInfo,
      GraphQLRequestParsedResult,
      GraphQLResolverExtras<any>
      > {}

        constructor

        constructor(
        operationType: any,
        predicate: any,
        endpoint: Path,
        resolver: ResponseResolver<GraphQLResolverExtras<any>, any, any>,
        options?: RequestHandlerOptions
        );

          property parsedRequestCache

          static parsedRequestCache: WeakMap<
          Request,
          ParsedGraphQLQuery & { query: string; variables?: GraphQLVariables }
          >;

            method extendResolverArgs

            protected extendResolverArgs: (args: {
            request: Request;
            parsedResult: GraphQLRequestParsedResult;
            }) => {
            query: string;
            operationType: OperationTypeNode;
            operationName: string;
            variables: GraphQLVariables;
            cookies: Record<string, string>;
            };

              method log

              log: (args: {
              request: Request;
              response: Response;
              parsedResult: GraphQLRequestParsedResult;
              }) => Promise<void>;

                method parse

                parse: (args: { request: Request }) => Promise<GraphQLRequestParsedResult>;

                  method parseGraphQLRequestOrGetFromCache

                  parseGraphQLRequestOrGetFromCache: (
                  request: Request
                  ) => Promise<ParsedGraphQLRequest<GraphQLVariables>>;
                  • Parses the request body, once per request, cached across all GraphQL handlers. This is done to avoid multiple parsing of the request body, which each requires a clone of the request.

                  method predicate

                  predicate: (args: {
                  request: Request;
                  parsedResult: GraphQLRequestParsedResult;
                  }) => Promise<boolean>;

                    method run

                    run: (args: {
                    request: StrictRequest<any>;
                    requestId: string;
                    resolutionContext?: ResponseResolutionContext;
                    }) => Promise<RequestHandlerExecutionResult<GraphQLRequestParsedResult> | null>;

                      class HttpHandler

                      class HttpHandler extends RequestHandler<
                      HttpHandlerInfo,
                      HttpRequestParsedResult,
                      HttpRequestResolverExtras<any>
                      > {}
                      • Request handler for HTTP requests. Provides request matching based on method and URL.

                      constructor

                      constructor(
                      method: HttpHandlerMethod,
                      predicate: HttpRequestPredicate<PathParams<string>>,
                      resolver: ResponseResolver<HttpRequestResolverExtras<any>, any, any>,
                      options?: RequestHandlerOptions
                      );

                        method extendResolverArgs

                        protected extendResolverArgs: (args: {
                        request: Request;
                        parsedResult: HttpRequestParsedResult;
                        }) => { params: PathParams<string>; cookies: Record<string, string> };

                          method log

                          log: (args: { request: Request; response: Response }) => Promise<void>;

                            method parse

                            parse: (args: {
                            request: Request;
                            resolutionContext?: ResponseResolutionContext;
                            }) => Promise<{ match: Match; cookies: Record<string, string> }>;

                              method predicate

                              predicate: (args: {
                              request: Request;
                              parsedResult: HttpRequestParsedResult;
                              resolutionContext?: ResponseResolutionContext;
                              }) => Promise<boolean>;

                                class HttpResponse

                                class HttpResponse<BodyType extends DefaultBodyType> extends FetchResponse {}
                                • A drop-in replacement for the standard Response class to allow additional features, like mocking the response Set-Cookie header.

                                  Example 1

                                  new HttpResponse('Hello world', { status: 201 }) HttpResponse.json({ name: 'John' }) HttpResponse.formData(form)

                                  See Also

                                constructor

                                constructor(body?: DefaultBodyType, init?: HttpResponseInit);

                                  property [bodyType]

                                  readonly [bodyType]: DefaultBodyType;

                                    method arrayBuffer

                                    static arrayBuffer: <BodyType extends ArrayBuffer | SharedArrayBuffer>(
                                    body?: BodyType,
                                    init?: HttpResponseInit
                                    ) => HttpResponse<BodyType>;
                                    • Create a Response with an ArrayBuffer body.

                                      Example 1

                                      const buffer = new ArrayBuffer(3) const view = new Uint8Array(buffer) view.set([1, 2, 3])

                                      HttpResponse.arrayBuffer(buffer)

                                    method error

                                    static error: () => HttpResponse<any>;

                                      method formData

                                      static formData: (
                                      body?: FormData,
                                      init?: HttpResponseInit
                                      ) => HttpResponse<FormData>;
                                      • Create a Response with a FormData body.

                                        Example 1

                                        const data = new FormData() data.set('name', 'Alice')

                                        HttpResponse.formData(data)

                                      method html

                                      static html: <BodyType extends string>(
                                      body?: BodyType | null,
                                      init?: HttpResponseInit
                                      ) => HttpResponse<BodyType>;
                                      • Create a Response with a Content-Type: "text/html" body.

                                        Example 1

                                        HttpResponse.html(<p class="author">Jane Doe</p>) HttpResponse.html(<main id="abc-123">Main text</main>, { status: 201 })

                                      method json

                                      static json: <BodyType extends JsonBodyType>(
                                      body?: NoInfer<BodyType> | null | undefined,
                                      init?: HttpResponseInit
                                      ) => HttpResponse<BodyType>;
                                      • Create a Response with a Content-Type: "application/json" body.

                                        Example 1

                                        HttpResponse.json({ firstName: 'John' }) HttpResponse.json({ error: 'Not Authorized' }, { status: 401 })

                                      method text

                                      static text: <BodyType extends string>(
                                      body?: NoInfer<BodyType> | null,
                                      init?: HttpResponseInit
                                      ) => HttpResponse<BodyType>;
                                      • Create a Response with a Content-Type: "text/plain" body.

                                        Example 1

                                        HttpResponse.text('hello world') HttpResponse.text('Error', { status: 500 })

                                      method xml

                                      static xml: <BodyType extends string>(
                                      body?: BodyType | null,
                                      init?: HttpResponseInit
                                      ) => HttpResponse<BodyType>;
                                      • Create a Response with a Content-Type: "application/xml" body.

                                        Example 1

                                        HttpResponse.xml(<user name="John" />) HttpResponse.xml(<article id="abc-123" />, { status: 201 })

                                      class RequestHandler

                                      abstract class RequestHandler<
                                      HandlerInfo extends RequestHandlerDefaultInfo = RequestHandlerDefaultInfo,
                                      ParsedResult extends Record<string, any> | undefined = any,
                                      ResolverExtras extends Record<string, unknown> = any,
                                      HandlerOptions extends RequestHandlerOptions = RequestHandlerOptions
                                      > {}

                                        constructor

                                        constructor(args: RequestHandlerArgs<HandlerInfo, HandlerOptions>);

                                          property cache

                                          static cache: WeakMap<
                                          StrictRequest<DefaultBodyType>,
                                          StrictRequest<DefaultBodyType>
                                          >;

                                            property info

                                            info: RequestHandlerDefaultInfo & RequestHandlerInternalInfo;

                                              property isUsed

                                              isUsed: boolean;
                                              • Indicates whether this request handler has been used (its resolver has successfully executed).

                                              property kind

                                              readonly kind: string;

                                                property resolver

                                                protected resolver: ResponseResolver<ResolverExtras, any, any>;

                                                  method extendResolverArgs

                                                  protected extendResolverArgs: (_args: {
                                                  request: Request;
                                                  parsedResult: ParsedResult;
                                                  }) => ResolverExtras;

                                                    method log

                                                    abstract log: (args: {
                                                    request: Request;
                                                    response: Response;
                                                    parsedResult: ParsedResult;
                                                    }) => void;
                                                    • Print out the successfully handled request.

                                                    method parse

                                                    parse: (_args: {
                                                    request: Request;
                                                    resolutionContext?: ResponseResolutionContext;
                                                    }) => Promise<ParsedResult>;
                                                    • Parse the intercepted request to extract additional information from it. Parsed result is then exposed to other methods of this request handler.

                                                    method predicate

                                                    abstract predicate: (args: {
                                                    request: Request;
                                                    parsedResult: ParsedResult;
                                                    resolutionContext?: ResponseResolutionContext;
                                                    }) => boolean | Promise<boolean>;
                                                    • Determine if the intercepted request should be mocked.

                                                    method reset

                                                    protected reset: () => void;
                                                    • Reset the runtime state accumulated during response resolution, such as generator iterator progress. Called when this handler is removed from the active handlers list so re-adding it later starts from a clean state.

                                                    method restore

                                                    protected restore: () => void;
                                                    • Restore this handler so it can match requests again after being exhausted (e.g. via { once: true }). Also clears any accumulated resolution state.

                                                    method run

                                                    run: (args: {
                                                    request: StrictRequest<any>;
                                                    requestId: string;
                                                    resolutionContext?: ResponseResolutionContext;
                                                    }) => Promise<RequestHandlerExecutionResult<ParsedResult> | null>;
                                                    • Execute this request handler and produce a mocked response using the given resolver function.

                                                    method test

                                                    test: (args: {
                                                    request: Request;
                                                    resolutionContext?: ResponseResolutionContext;
                                                    }) => Promise<boolean>;
                                                    • Test if this handler matches the given request.

                                                      This method is not used internally but is exposed as a convenience method for consumers writing custom handlers.

                                                    class SetupApi

                                                    abstract class SetupApi<EventMap extends DefaultEventMap> extends Disposable {}
                                                    • Generic class for the mock API setup. Preserved only for backward compatibility.

                                                      Deprecated

                                                    constructor

                                                    constructor(...initialHandlers: AnyHandler[]);

                                                      property emitter

                                                      protected emitter: Emitter<EventMap>;

                                                        property events

                                                        readonly events: LifeCycleEventEmitter<EventMap>;

                                                          property handlersController

                                                          protected handlersController: HandlersController;

                                                            property publicEmitter

                                                            protected publicEmitter: Emitter<EventMap>;

                                                              method listHandlers

                                                              listHandlers: () => ReadonlyArray<AnyHandler>;

                                                                method resetHandlers

                                                                resetHandlers: (...nextHandlers: Array<AnyHandler>) => void;

                                                                  method restoreHandlers

                                                                  restoreHandlers: () => void;

                                                                    method use

                                                                    use: (...runtimeHandlers: Array<AnyHandler>) => void;

                                                                      class WebSocketHandler

                                                                      class WebSocketHandler {}

                                                                        constructor

                                                                        constructor(url: Path);

                                                                          property [kEmitter]

                                                                          protected [kEmitter]: Emitter<WebSocketHandlerEventMap>;

                                                                            property callFrame

                                                                            callFrame?: string;

                                                                              property id

                                                                              id: string;

                                                                                property kind

                                                                                kind: string;

                                                                                  property url

                                                                                  protected readonly url: Path;

                                                                                    method [kConnect]

                                                                                    protected [kConnect]: (connection: WebSocketHandlerConnection) => boolean;

                                                                                      method log

                                                                                      log: (connection: WebSocketConnectionData) => () => void;

                                                                                        method parse

                                                                                        parse: (args: {
                                                                                        url: string | URL;
                                                                                        resolutionContext?: WebSocketResolutionContext;
                                                                                        }) => WebSocketHandlerParsedResult;

                                                                                          method predicate

                                                                                          predicate: (args: {
                                                                                          url: string | URL;
                                                                                          parsedResult: WebSocketHandlerParsedResult;
                                                                                          }) => boolean;

                                                                                            method run

                                                                                            run: (
                                                                                            connection: WebSocketConnectionData,
                                                                                            resolutionContext?: WebSocketResolutionContext
                                                                                            ) => Promise<WebSocketHandlerConnection | null>;

                                                                                              method test

                                                                                              test: (
                                                                                              url: string | URL,
                                                                                              resolutionContext?: WebSocketResolutionContext & { strict?: boolean }
                                                                                              ) => boolean;

                                                                                                Interfaces

                                                                                                interface GraphQLJsonRequestBody

                                                                                                interface GraphQLJsonRequestBody<Variables extends GraphQLVariables> {}

                                                                                                  property query

                                                                                                  query: string;

                                                                                                    property variables

                                                                                                    variables?: Variables;

                                                                                                      interface GraphQLLinkHandlers

                                                                                                      interface GraphQLLinkHandlers {}

                                                                                                        property mutation

                                                                                                        mutation: GraphQLRequestHandler;

                                                                                                          property operation

                                                                                                          operation: GraphQLOperationHandler;

                                                                                                            property query

                                                                                                            query: GraphQLRequestHandler;

                                                                                                              interface HandleRequestOptions

                                                                                                              interface HandleRequestOptions {}

                                                                                                                property resolutionContext

                                                                                                                resolutionContext?: ResponseResolutionContext;
                                                                                                                • resolutionContext is not part of the general public api but is exposed to aid in creating extensions like @mswjs/http-middleware.

                                                                                                                method onMockedResponse

                                                                                                                onMockedResponse: (
                                                                                                                response: Response,
                                                                                                                handler: RequiredDeep<HandlersExecutionResult>
                                                                                                                ) => void;
                                                                                                                • Invoked when the mocked response is ready to be sent.

                                                                                                                method onPassthroughResponse

                                                                                                                onPassthroughResponse: (request: Request) => void;
                                                                                                                • Invoked whenever a request is performed as-is.

                                                                                                                interface HttpHandlerInfo

                                                                                                                interface HttpHandlerInfo extends RequestHandlerDefaultInfo {}

                                                                                                                  property method

                                                                                                                  method: HttpHandlerMethod;

                                                                                                                    property path

                                                                                                                    path: HttpRequestPredicate<PathParams>;

                                                                                                                      interface HttpResponseInit

                                                                                                                      interface HttpResponseInit extends ResponseInit {}

                                                                                                                        property type

                                                                                                                        type?: ResponseType;

                                                                                                                          interface Match

                                                                                                                          interface Match {}

                                                                                                                            property matches

                                                                                                                            matches: boolean;

                                                                                                                              property params

                                                                                                                              params?: PathParams;

                                                                                                                                interface RequestHandlerOptions

                                                                                                                                interface RequestHandlerOptions {}

                                                                                                                                  property once

                                                                                                                                  once?: boolean;

                                                                                                                                    interface ResponseResolutionContext

                                                                                                                                    interface ResponseResolutionContext {}

                                                                                                                                      property baseUrl

                                                                                                                                      baseUrl?: string;
                                                                                                                                      • A base url to use when resolving relative urls. This is primarily used by the @mswjs/http-middleware to resolve relative urls in the context of the running server

                                                                                                                                      property quiet

                                                                                                                                      quiet?: boolean;

                                                                                                                                        interface SharedOptions

                                                                                                                                        interface SharedOptions {}

                                                                                                                                          property onUnhandledRequest

                                                                                                                                          onUnhandledRequest?: UnhandledRequestStrategy;
                                                                                                                                          • Specifies how to react to a request that has no corresponding request handler. Warns on unhandled requests by default.

                                                                                                                                            Example 1

                                                                                                                                            worker.start({ onUnhandledRequest: 'bypass' })

                                                                                                                                            Example 2

                                                                                                                                            worker.start({ onUnhandledRequest: 'warn' })

                                                                                                                                            Example 3

                                                                                                                                            server.listen({ onUnhandledRequest: 'error' })

                                                                                                                                          interface StrictRequest

                                                                                                                                          interface StrictRequest<BodyType extends JsonBodyType> extends Request {}

                                                                                                                                            method clone

                                                                                                                                            clone: () => StrictRequest<BodyType>;

                                                                                                                                              method json

                                                                                                                                              json: () => Promise<BodyType>;

                                                                                                                                                interface WebSocketHandlerConnection

                                                                                                                                                interface WebSocketHandlerConnection {}

                                                                                                                                                  property client

                                                                                                                                                  client: WebSocketClientConnectionProtocol;

                                                                                                                                                    property info

                                                                                                                                                    info: WebSocketConnectionData['info'];

                                                                                                                                                      property params

                                                                                                                                                      params: PathParams;

                                                                                                                                                        property server

                                                                                                                                                        server: WebSocketServerConnectionProtocol;

                                                                                                                                                          Enums

                                                                                                                                                          enum HttpMethods

                                                                                                                                                          enum HttpMethods {
                                                                                                                                                          HEAD = 'HEAD',
                                                                                                                                                          GET = 'GET',
                                                                                                                                                          POST = 'POST',
                                                                                                                                                          PUT = 'PUT',
                                                                                                                                                          PATCH = 'PATCH',
                                                                                                                                                          OPTIONS = 'OPTIONS',
                                                                                                                                                          DELETE = 'DELETE',
                                                                                                                                                          }

                                                                                                                                                            member DELETE

                                                                                                                                                            DELETE = 'DELETE'

                                                                                                                                                              member GET

                                                                                                                                                              GET = 'GET'

                                                                                                                                                                member HEAD

                                                                                                                                                                HEAD = 'HEAD'

                                                                                                                                                                  member OPTIONS

                                                                                                                                                                  OPTIONS = 'OPTIONS'

                                                                                                                                                                    member PATCH

                                                                                                                                                                    PATCH = 'PATCH'

                                                                                                                                                                      member POST

                                                                                                                                                                      POST = 'POST'

                                                                                                                                                                        member PUT

                                                                                                                                                                        PUT = 'PUT'

                                                                                                                                                                          Type Aliases

                                                                                                                                                                          type AnyHandler

                                                                                                                                                                          type AnyHandler = RequestHandler | WebSocketHandler;

                                                                                                                                                                            type AsyncResponseResolverReturnType

                                                                                                                                                                            type AsyncResponseResolverReturnType<ResponseBodyType extends DefaultBodyType> =
                                                                                                                                                                            MaybePromise<
                                                                                                                                                                            | ResponseResolverReturnType<ResponseBodyType>
                                                                                                                                                                            | Iterable<
                                                                                                                                                                            MaybeAsyncResponseResolverReturnType<ResponseBodyType>,
                                                                                                                                                                            MaybeAsyncResponseResolverReturnType<ResponseBodyType>,
                                                                                                                                                                            MaybeAsyncResponseResolverReturnType<ResponseBodyType>
                                                                                                                                                                            >
                                                                                                                                                                            | AsyncIterable<
                                                                                                                                                                            MaybeAsyncResponseResolverReturnType<ResponseBodyType>,
                                                                                                                                                                            MaybeAsyncResponseResolverReturnType<ResponseBodyType>,
                                                                                                                                                                            MaybeAsyncResponseResolverReturnType<ResponseBodyType>
                                                                                                                                                                            >
                                                                                                                                                                            >;

                                                                                                                                                                              type DefaultBodyType

                                                                                                                                                                              type DefaultBodyType =
                                                                                                                                                                              | Record<string, any>
                                                                                                                                                                              | DefaultRequestMultipartBody
                                                                                                                                                                              | string
                                                                                                                                                                              | number
                                                                                                                                                                              | boolean
                                                                                                                                                                              | null
                                                                                                                                                                              | undefined;

                                                                                                                                                                                type DefaultRequestMultipartBody

                                                                                                                                                                                type DefaultRequestMultipartBody = Record<
                                                                                                                                                                                string,
                                                                                                                                                                                string | File | Array<string | File>
                                                                                                                                                                                >;

                                                                                                                                                                                  type DelayMode

                                                                                                                                                                                  type DelayMode = 'real' | 'infinite';

                                                                                                                                                                                    type GraphQLCustomPredicate

                                                                                                                                                                                    type GraphQLCustomPredicate = (args: {
                                                                                                                                                                                    request: Request;
                                                                                                                                                                                    query: string;
                                                                                                                                                                                    operationType: GraphQLOperationType;
                                                                                                                                                                                    operationName: string;
                                                                                                                                                                                    variables: GraphQLVariables;
                                                                                                                                                                                    cookies: Record<string, string>;
                                                                                                                                                                                    }) => GraphQLCustomPredicateResult | Promise<GraphQLCustomPredicateResult>;

                                                                                                                                                                                      type GraphQLOperationHandler

                                                                                                                                                                                      type GraphQLOperationHandler = <
                                                                                                                                                                                      Query extends GraphQLQuery = GraphQLQuery,
                                                                                                                                                                                      Variables extends GraphQLVariables = GraphQLVariables
                                                                                                                                                                                      >(
                                                                                                                                                                                      resolver: GraphQLResponseResolver<
                                                                                                                                                                                      [Query] extends [never] ? GraphQLQuery : Query,
                                                                                                                                                                                      Variables
                                                                                                                                                                                      >,
                                                                                                                                                                                      options?: RequestHandlerOptions
                                                                                                                                                                                      ) => GraphQLHandler;

                                                                                                                                                                                        type GraphQLOperationType

                                                                                                                                                                                        type GraphQLOperationType = OperationTypeNode | 'all';

                                                                                                                                                                                          type GraphQLQuery

                                                                                                                                                                                          type GraphQLQuery = Record<string, any> | null;

                                                                                                                                                                                            type GraphQLRequestBody

                                                                                                                                                                                            type GraphQLRequestBody<VariablesType extends GraphQLVariables> =
                                                                                                                                                                                            | GraphQLJsonRequestBody<VariablesType>
                                                                                                                                                                                            | GraphQLMultipartRequestBody
                                                                                                                                                                                            | Record<string, any>
                                                                                                                                                                                            | undefined;

                                                                                                                                                                                              type GraphQLRequestHandler

                                                                                                                                                                                              type GraphQLRequestHandler = <
                                                                                                                                                                                              Query extends GraphQLQuery = GraphQLQuery,
                                                                                                                                                                                              Variables extends GraphQLVariables = GraphQLVariables
                                                                                                                                                                                              >(
                                                                                                                                                                                              predicate: GraphQLPredicate<Query, Variables>,
                                                                                                                                                                                              resolver: GraphQLResponseResolver<
                                                                                                                                                                                              [Query] extends [never] ? GraphQLQuery : Query,
                                                                                                                                                                                              Variables
                                                                                                                                                                                              >,
                                                                                                                                                                                              options?: RequestHandlerOptions
                                                                                                                                                                                              ) => GraphQLHandler;

                                                                                                                                                                                                type GraphQLResponseBody

                                                                                                                                                                                                type GraphQLResponseBody<BodyType extends DefaultBodyType> =
                                                                                                                                                                                                | {
                                                                                                                                                                                                data?: BodyType | null;
                                                                                                                                                                                                errors?: readonly Partial<GraphQLError>[] | null;
                                                                                                                                                                                                extensions?: Record<string, any>;
                                                                                                                                                                                                }
                                                                                                                                                                                                | null
                                                                                                                                                                                                | undefined;

                                                                                                                                                                                                  type GraphQLResponseResolver

                                                                                                                                                                                                  type GraphQLResponseResolver<
                                                                                                                                                                                                  Query extends GraphQLQuery = GraphQLQuery,
                                                                                                                                                                                                  Variables extends GraphQLVariables = GraphQLVariables
                                                                                                                                                                                                  > = ResponseResolver<
                                                                                                                                                                                                  GraphQLResolverExtras<Variables>,
                                                                                                                                                                                                  null,
                                                                                                                                                                                                  GraphQLResponseBody<[Query] extends [never] ? GraphQLQuery : Query>
                                                                                                                                                                                                  >;

                                                                                                                                                                                                    type GraphQLVariables

                                                                                                                                                                                                    type GraphQLVariables = Record<string, any>;

                                                                                                                                                                                                      type HttpCustomPredicate

                                                                                                                                                                                                      type HttpCustomPredicate<Params extends PathParams> = (args: {
                                                                                                                                                                                                      request: Request;
                                                                                                                                                                                                      cookies: Record<string, string>;
                                                                                                                                                                                                      }) => HttpCustomPredicateResult<Params> | Promise<HttpCustomPredicateResult<Params>>;

                                                                                                                                                                                                        type HttpHandlerMethod

                                                                                                                                                                                                        type HttpHandlerMethod = string | RegExp;

                                                                                                                                                                                                          type HttpRequestHandler

                                                                                                                                                                                                          type HttpRequestHandler = <
                                                                                                                                                                                                          Params extends PathParams<keyof Params> = PathParams,
                                                                                                                                                                                                          RequestBodyType extends DefaultBodyType = DefaultBodyType,
                                                                                                                                                                                                          ResponseBodyType extends DefaultBodyType = undefined
                                                                                                                                                                                                          >(
                                                                                                                                                                                                          predicate: HttpRequestPredicate<Params>,
                                                                                                                                                                                                          resolver: HttpResponseResolver<Params, RequestBodyType, ResponseBodyType>,
                                                                                                                                                                                                          options?: RequestHandlerOptions
                                                                                                                                                                                                          ) => HttpHandler;

                                                                                                                                                                                                            type HttpRequestParsedResult

                                                                                                                                                                                                            type HttpRequestParsedResult = {
                                                                                                                                                                                                            match: Match;
                                                                                                                                                                                                            cookies: Record<string, string>;
                                                                                                                                                                                                            };

                                                                                                                                                                                                              type HttpRequestResolverExtras

                                                                                                                                                                                                              type HttpRequestResolverExtras<Params extends PathParams> = {
                                                                                                                                                                                                              params: Params;
                                                                                                                                                                                                              cookies: Record<string, string>;
                                                                                                                                                                                                              };

                                                                                                                                                                                                                type HttpResponseResolver

                                                                                                                                                                                                                type HttpResponseResolver<
                                                                                                                                                                                                                Params extends PathParams<keyof Params> = PathParams,
                                                                                                                                                                                                                RequestBodyType extends DefaultBodyType = DefaultBodyType,
                                                                                                                                                                                                                ResponseBodyType extends DefaultBodyType = DefaultBodyType
                                                                                                                                                                                                                > = ResponseResolver<
                                                                                                                                                                                                                HttpRequestResolverExtras<Params>,
                                                                                                                                                                                                                RequestBodyType,
                                                                                                                                                                                                                ResponseBodyType
                                                                                                                                                                                                                >;

                                                                                                                                                                                                                  type JsonBodyType

                                                                                                                                                                                                                  type JsonBodyType =
                                                                                                                                                                                                                  | Record<string, any>
                                                                                                                                                                                                                  | string
                                                                                                                                                                                                                  | number
                                                                                                                                                                                                                  | boolean
                                                                                                                                                                                                                  | null
                                                                                                                                                                                                                  | undefined;

                                                                                                                                                                                                                    type LifeCycleEventsMap

                                                                                                                                                                                                                    type LifeCycleEventsMap = {
                                                                                                                                                                                                                    'request:start': [
                                                                                                                                                                                                                    args: {
                                                                                                                                                                                                                    request: Request;
                                                                                                                                                                                                                    requestId: string;
                                                                                                                                                                                                                    }
                                                                                                                                                                                                                    ];
                                                                                                                                                                                                                    'request:match': [
                                                                                                                                                                                                                    args: {
                                                                                                                                                                                                                    request: Request;
                                                                                                                                                                                                                    requestId: string;
                                                                                                                                                                                                                    }
                                                                                                                                                                                                                    ];
                                                                                                                                                                                                                    'request:unhandled': [
                                                                                                                                                                                                                    args: {
                                                                                                                                                                                                                    request: Request;
                                                                                                                                                                                                                    requestId: string;
                                                                                                                                                                                                                    }
                                                                                                                                                                                                                    ];
                                                                                                                                                                                                                    'request:end': [
                                                                                                                                                                                                                    args: {
                                                                                                                                                                                                                    request: Request;
                                                                                                                                                                                                                    requestId: string;
                                                                                                                                                                                                                    }
                                                                                                                                                                                                                    ];
                                                                                                                                                                                                                    'response:mocked': [
                                                                                                                                                                                                                    args: {
                                                                                                                                                                                                                    response: Response;
                                                                                                                                                                                                                    request: Request;
                                                                                                                                                                                                                    requestId: string;
                                                                                                                                                                                                                    }
                                                                                                                                                                                                                    ];
                                                                                                                                                                                                                    'response:bypass': [
                                                                                                                                                                                                                    args: {
                                                                                                                                                                                                                    response: Response;
                                                                                                                                                                                                                    request: Request;
                                                                                                                                                                                                                    requestId: string;
                                                                                                                                                                                                                    }
                                                                                                                                                                                                                    ];
                                                                                                                                                                                                                    unhandledException: [
                                                                                                                                                                                                                    args: {
                                                                                                                                                                                                                    error: Error;
                                                                                                                                                                                                                    request: Request;
                                                                                                                                                                                                                    requestId: string;
                                                                                                                                                                                                                    }
                                                                                                                                                                                                                    ];
                                                                                                                                                                                                                    };
                                                                                                                                                                                                                    • Deprecated

                                                                                                                                                                                                                      Please use HttpNetworkFrameEventMap or WebSocketNetworkFrameEventMap instead.

                                                                                                                                                                                                                    type ParsedGraphQLRequest

                                                                                                                                                                                                                    type ParsedGraphQLRequest<
                                                                                                                                                                                                                    VariablesType extends GraphQLVariables = GraphQLVariables
                                                                                                                                                                                                                    > =
                                                                                                                                                                                                                    | (ParsedGraphQLQuery & {
                                                                                                                                                                                                                    query: string;
                                                                                                                                                                                                                    variables?: VariablesType;
                                                                                                                                                                                                                    })
                                                                                                                                                                                                                    | undefined;

                                                                                                                                                                                                                      type Path

                                                                                                                                                                                                                      type Path = string | RegExp;

                                                                                                                                                                                                                        type PathParams

                                                                                                                                                                                                                        type PathParams<KeyType extends keyof any = string> = {
                                                                                                                                                                                                                        [ParamName in KeyType]?: string | ReadonlyArray<string>;
                                                                                                                                                                                                                        };

                                                                                                                                                                                                                          type RequestQuery

                                                                                                                                                                                                                          type RequestQuery = {
                                                                                                                                                                                                                          [queryName: string]: string;
                                                                                                                                                                                                                          };

                                                                                                                                                                                                                            type ResponseResolver

                                                                                                                                                                                                                            type ResponseResolver<
                                                                                                                                                                                                                            ResolverExtraInfo extends Record<string, unknown> = Record<string, unknown>,
                                                                                                                                                                                                                            RequestBodyType extends DefaultBodyType = DefaultBodyType,
                                                                                                                                                                                                                            ResponseBodyType extends DefaultBodyType = undefined
                                                                                                                                                                                                                            > = (
                                                                                                                                                                                                                            info: ResponseResolverInfo<ResolverExtraInfo, RequestBodyType>
                                                                                                                                                                                                                            ) => AsyncResponseResolverReturnType<ResponseBodyType>;

                                                                                                                                                                                                                              type ResponseResolverInfo

                                                                                                                                                                                                                              type ResponseResolverInfo<
                                                                                                                                                                                                                              ResolverExtraInfo extends Record<string, unknown>,
                                                                                                                                                                                                                              RequestBodyType extends DefaultBodyType = DefaultBodyType
                                                                                                                                                                                                                              > = {
                                                                                                                                                                                                                              request: StrictRequest<RequestBodyType>;
                                                                                                                                                                                                                              requestId: string;
                                                                                                                                                                                                                              /**
                                                                                                                                                                                                                              * Schedule a callback to run after this response resolver completes.
                                                                                                                                                                                                                              * Handy for cleaning up the side effects introduced in the resolver.
                                                                                                                                                                                                                              * @example
                                                                                                                                                                                                                              * sse('/', ({ client, finalize }) => {
                                                                                                                                                                                                                              * const interval = setInterval(() => client.send({ data: 'ping' }))
                                                                                                                                                                                                                              * finalize(() => clearInterval(interval))
                                                                                                                                                                                                                              * })
                                                                                                                                                                                                                              */
                                                                                                                                                                                                                              finalize: ResponseResolverFinalizeFunction;
                                                                                                                                                                                                                              } & ResolverExtraInfo;

                                                                                                                                                                                                                                type ResponseResolverReturnType

                                                                                                                                                                                                                                type ResponseResolverReturnType<
                                                                                                                                                                                                                                ResponseBodyType extends DefaultBodyType = undefined
                                                                                                                                                                                                                                > =
                                                                                                                                                                                                                                | ([ResponseBodyType] extends [undefined]
                                                                                                                                                                                                                                ? Response
                                                                                                                                                                                                                                : ResponseBodyType extends GraphQLRequestBody<any>
                                                                                                                                                                                                                                ? HttpResponse<ResponseBodyType> | DefaultUnsafeFetchResponse
                                                                                                                                                                                                                                : HttpResponse<ResponseBodyType>)
                                                                                                                                                                                                                                | undefined
                                                                                                                                                                                                                                | void;

                                                                                                                                                                                                                                  type ServerSentEventMessage

                                                                                                                                                                                                                                  type ServerSentEventMessage<
                                                                                                                                                                                                                                  EventMap extends EventMapConstraint = {
                                                                                                                                                                                                                                  message: unknown;
                                                                                                                                                                                                                                  }
                                                                                                                                                                                                                                  > =
                                                                                                                                                                                                                                  | ToEventDiscriminatedUnion<
                                                                                                                                                                                                                                  EventMap & {
                                                                                                                                                                                                                                  message: unknown;
                                                                                                                                                                                                                                  }
                                                                                                                                                                                                                                  >
                                                                                                                                                                                                                                  | {
                                                                                                                                                                                                                                  id?: never;
                                                                                                                                                                                                                                  event?: never;
                                                                                                                                                                                                                                  data?: never;
                                                                                                                                                                                                                                  retry: number;
                                                                                                                                                                                                                                  };

                                                                                                                                                                                                                                    type ServerSentEventRequestHandler

                                                                                                                                                                                                                                    type ServerSentEventRequestHandler = <
                                                                                                                                                                                                                                    EventMap extends EventMapConstraint = {
                                                                                                                                                                                                                                    message: unknown;
                                                                                                                                                                                                                                    },
                                                                                                                                                                                                                                    Params extends PathParams<keyof Params> = PathParams,
                                                                                                                                                                                                                                    RequestPath extends Path = Path
                                                                                                                                                                                                                                    >(
                                                                                                                                                                                                                                    path: RequestPath,
                                                                                                                                                                                                                                    resolver: ServerSentEventResolver<EventMap, Params>
                                                                                                                                                                                                                                    ) => HttpHandler;

                                                                                                                                                                                                                                      type ServerSentEventResolver

                                                                                                                                                                                                                                      type ServerSentEventResolver<
                                                                                                                                                                                                                                      EventMap extends EventMapConstraint,
                                                                                                                                                                                                                                      Params extends PathParams
                                                                                                                                                                                                                                      > = ResponseResolver<ServerSentEventResolverExtras<EventMap, Params>, any, any>;

                                                                                                                                                                                                                                        type ServerSentEventResolverExtras

                                                                                                                                                                                                                                        type ServerSentEventResolverExtras<
                                                                                                                                                                                                                                        EventMap extends EventMapConstraint,
                                                                                                                                                                                                                                        Params extends PathParams
                                                                                                                                                                                                                                        > = HttpRequestResolverExtras<Params> & {
                                                                                                                                                                                                                                        client: ServerSentEventClient<EventMap>;
                                                                                                                                                                                                                                        server: ServerSentEventServer;
                                                                                                                                                                                                                                        };

                                                                                                                                                                                                                                          type StrictResponse

                                                                                                                                                                                                                                          type StrictResponse<BodyType extends DefaultBodyType> = HttpResponse<BodyType>;
                                                                                                                                                                                                                                          • Opaque Response type that supports strict body type.

                                                                                                                                                                                                                                            Deprecated

                                                                                                                                                                                                                                            Please use HttpResponse instead.

                                                                                                                                                                                                                                          type UnhandledRequestCallback

                                                                                                                                                                                                                                          type UnhandledRequestCallback = (
                                                                                                                                                                                                                                          request: Request,
                                                                                                                                                                                                                                          print: UnhandledRequestPrint
                                                                                                                                                                                                                                          ) => void;

                                                                                                                                                                                                                                            type UnhandledRequestStrategy

                                                                                                                                                                                                                                            type UnhandledRequestStrategy =
                                                                                                                                                                                                                                            | 'bypass'
                                                                                                                                                                                                                                            | 'warn'
                                                                                                                                                                                                                                            | 'error'
                                                                                                                                                                                                                                            | UnhandledRequestCallback;

                                                                                                                                                                                                                                              type WebSocketEventListener

                                                                                                                                                                                                                                              type WebSocketEventListener<EventType extends keyof WebSocketHandlerEventMap> = (
                                                                                                                                                                                                                                              ...args: WebSocketHandlerEventMap[EventType]
                                                                                                                                                                                                                                              ) => void;

                                                                                                                                                                                                                                                type WebSocketHandlerEventMap

                                                                                                                                                                                                                                                type WebSocketHandlerEventMap = {
                                                                                                                                                                                                                                                connection: [args: WebSocketHandlerConnection];
                                                                                                                                                                                                                                                };
                                                                                                                                                                                                                                                  type WebSocketLink = {
                                                                                                                                                                                                                                                  /**
                                                                                                                                                                                                                                                  * A set of all WebSocket clients connected
                                                                                                                                                                                                                                                  * to this link.
                                                                                                                                                                                                                                                  *
                                                                                                                                                                                                                                                  * @see {@link https://mswjs.io/docs/api/ws#clients `clients` API reference}
                                                                                                                                                                                                                                                  */
                                                                                                                                                                                                                                                  clients: Set<WebSocketClientConnectionProtocol>;
                                                                                                                                                                                                                                                  /**
                                                                                                                                                                                                                                                  * Adds an event listener to this WebSocket link.
                                                                                                                                                                                                                                                  *
                                                                                                                                                                                                                                                  * @example
                                                                                                                                                                                                                                                  * const chat = ws.link('wss://chat.example.com')
                                                                                                                                                                                                                                                  * chat.addEventListener('connection', listener)
                                                                                                                                                                                                                                                  *
                                                                                                                                                                                                                                                  * @see {@link https://mswjs.io/docs/api/ws#onevent-listener `on()` API reference}
                                                                                                                                                                                                                                                  */
                                                                                                                                                                                                                                                  addEventListener: <EventType extends keyof WebSocketHandlerEventMap>(
                                                                                                                                                                                                                                                  event: EventType,
                                                                                                                                                                                                                                                  listener: WebSocketEventListener<EventType>
                                                                                                                                                                                                                                                  ) => WebSocketHandler;
                                                                                                                                                                                                                                                  /**
                                                                                                                                                                                                                                                  * Broadcasts the given data to all WebSocket clients.
                                                                                                                                                                                                                                                  *
                                                                                                                                                                                                                                                  * @example
                                                                                                                                                                                                                                                  * const service = ws.link('wss://example.com')
                                                                                                                                                                                                                                                  * service.addEventListener('connection', () => {
                                                                                                                                                                                                                                                  * service.broadcast('hello, everyone!')
                                                                                                                                                                                                                                                  * })
                                                                                                                                                                                                                                                  *
                                                                                                                                                                                                                                                  * @see {@link https://mswjs.io/docs/api/ws#broadcastdata `broadcast()` API reference}
                                                                                                                                                                                                                                                  */
                                                                                                                                                                                                                                                  broadcast: (data: WebSocketData) => void;
                                                                                                                                                                                                                                                  /**
                                                                                                                                                                                                                                                  * Broadcasts the given data to all WebSocket clients
                                                                                                                                                                                                                                                  * except the ones provided in the `clients` argument.
                                                                                                                                                                                                                                                  *
                                                                                                                                                                                                                                                  * @example
                                                                                                                                                                                                                                                  * const service = ws.link('wss://example.com')
                                                                                                                                                                                                                                                  * service.addEventListener('connection', ({ client }) => {
                                                                                                                                                                                                                                                  * service.broadcastExcept(client, 'hi, the rest of you!')
                                                                                                                                                                                                                                                  * })
                                                                                                                                                                                                                                                  *
                                                                                                                                                                                                                                                  * @see {@link https://mswjs.io/docs/api/ws#broadcastexceptclients-data `broadcast()` API reference}
                                                                                                                                                                                                                                                  */
                                                                                                                                                                                                                                                  broadcastExcept: (
                                                                                                                                                                                                                                                  clients:
                                                                                                                                                                                                                                                  | WebSocketClientConnectionProtocol
                                                                                                                                                                                                                                                  | Array<WebSocketClientConnectionProtocol>,
                                                                                                                                                                                                                                                  data: WebSocketData
                                                                                                                                                                                                                                                  ) => void;
                                                                                                                                                                                                                                                  };

                                                                                                                                                                                                                                                    Package Files (20)

                                                                                                                                                                                                                                                    Dependencies (18)

                                                                                                                                                                                                                                                    Dev Dependencies (45)

                                                                                                                                                                                                                                                    Peer Dependencies (1)

                                                                                                                                                                                                                                                    Badge

                                                                                                                                                                                                                                                    To add a badge like this onejsDocs.io badgeto your package's README, use the codes available below.

                                                                                                                                                                                                                                                    You may also use Shields.io to create a custom badge linking to https://www.jsdocs.io/package/msw.

                                                                                                                                                                                                                                                    • Markdown
                                                                                                                                                                                                                                                      [![jsDocs.io](https://img.shields.io/badge/jsDocs.io-reference-blue)](https://www.jsdocs.io/package/msw)
                                                                                                                                                                                                                                                    • HTML
                                                                                                                                                                                                                                                      <a href="https://www.jsdocs.io/package/msw"><img src="https://img.shields.io/badge/jsDocs.io-reference-blue" alt="jsDocs.io"></a>