Skip to main content

HttpInterceptor

HTTP interceptors provide the main API to handle HTTP requests and return mock responses. The methods, paths, status codes, parameters, and responses are statically typed based on the service schema.

interceptor.baseURL

The base URL used by the interceptor.

Type: string

interceptor.requestSaving

Configures if the intercepted requests are saved and how they are handled.

Type: HttpInterceptorRequestSaving

  • enabled: boolean | undefined (default: process.env.NODE_ENV === 'test')

    Whether request handlers should save their intercepted requests in memory and make them accessible through handler.requests.

    If you are using interceptor.checkTimes() or handler.checkTimes() during tests, consider enabling this option to get more detailed information in TimesCheckError errors.

    INFO: Clearing the interceptor when saving requests

    If request saving is enabled, make sure to regularly clear the interceptor to avoid requests accumulating in memory. A common practice is to call interceptor.clear() after each test.

  • safeLimit: number | undefined (default: 1000)

    The safe number of requests to save in memory before logging warnings in the console. If requestSaving.enabled is true and the interceptor is not regularly cleared with interceptor.clear(), the requests may accumulate in memory and cause performance issues. This option does not limit the number of requests saved in memory, only when to log warnings.

Related:

interceptor.onUnhandledRequest

The strategy to use for unhandled requests. If a request starts with the base URL of the interceptor, but no matching handler exists, this strategy will be used. If a function is provided, it will be called with the unhandled request

Type: UnhandledRequestStrategy | undefined

  • action: 'bypass' | 'reject'

    The action to take when an unhandled request is intercepted. When set to 'bypass', the request will be allowed to pass through and reach the real network. When set to 'reject', the request will be rejected with a network error. Local interceptor can use bypass or reject, while remote interceptors only support reject, since unhandled requests that reach an interceptor server cannot be bypassed.

  • log: boolean (default: true)

    Whether to log unhandled requests to the console.

Related:

interceptor.auth

The options to authenticate a remote interceptor when connecting to an interceptor server. This is required if the interceptor server was started with the --tokens-dir option.

Type: HttpInterceptorAuthOptions | undefined

  • token: string

    The authentication token to use.

Related:

interceptor.platform

The platform the interceptor is running on. null if the interceptor is not running.

Type: HttpInterceptorPlatform | null (readonly)

interceptor.isRunning

Whether the interceptor is currently running and ready to use.

Type: boolean (readonly)

interceptor.start()

Starts the interceptor, allowing it to intercept HTTP requests.

await interceptor.start();

Returns: Promise<void>

INFO: Local interceptors in browsers

If you are using a local interceptor in a browser environment, you must first initialize a mock service worker in your public directory before starting the interceptor.

INFO: Remote interceptors and interceptor servers

If you are using a remote interceptor, the baseURL should point to a running interceptor server, which is configured by the interceptor to handle requests. Learn more about starting remote HTTP interceptors.

interceptor.stop()

Stops the interceptor, preventing it from intercepting HTTP requests. Stopped interceptors are automatically cleared, exactly as if interceptor.clear() had been called.

await interceptor.stop();

Returns: Promise<void>

Declaring request handlers

After a request is intercepted, Zimic tries to find a handler that matches it, considering the base URL of the interceptor, and the method, path, restrictions, and limits on the number of requests of the handler.

The handlers are checked from the last one created to the first one, so new handlers have preference over older ones. This allows you to declare generic and specific handlers based on their order of creation. For example, a generic handler for GET /users can return an empty list, while a specific handler in a test case can return a list with some users. In this case, the specific handler will be considered first as long as it is created after the generic one.

Related:

interceptor.get()

Creates a GET HttpRequestHandler for a path declared in the interceptor schema.

interceptor.get(path);

Arguments:

  • path: string

    The path to intercept. Paths with dynamic parameters, such as /users/:id, are supported, but you need to specify the original path as a type parameter to get type-inference and type-validation.

Returns: LocalHttpRequestHandler<Schema, 'GET', Path>

interceptor.post()

Creates a POST HttpRequestHandler for a path declared in the interceptor schema.

interceptor.post(path);

Arguments:

  • path: string

    The path to intercept. Paths with dynamic parameters, such as /users/:id, are supported, but you need to specify the original path as a type parameter to get type-inference and type-validation.

Returns: LocalHttpRequestHandler<Schema, 'POST', Path>

interceptor.put()

Creates a PUT HttpRequestHandler for a path declared in the interceptor schema.

interceptor.put(path);

Arguments:

  • path: string

    The path to intercept. Paths with dynamic parameters, such as /users/:id, are supported, but you need to specify the original path as a type parameter to get type-inference and type-validation.

Returns: LocalHttpRequestHandler<Schema, 'PUT', Path>

interceptor.patch()

Creates a PATCH HttpRequestHandler for a path declared in the interceptor schema.

interceptor.patch(path);

Arguments:

  • path: string

    The path to intercept. Paths with dynamic parameters, such as /users/:id, are supported, but you need to specify the original path as a type parameter to get type-inference and type-validation.

Returns: LocalHttpRequestHandler<Schema, 'PATCH', Path>

interceptor.delete()

Creates a DELETE HttpRequestHandler for a path declared in the interceptor schema.

interceptor.delete(path);

Arguments:

  • path: string

    The path to intercept. Paths with dynamic parameters, such as /users/:id, are supported, but you need to specify the original path as a type parameter to get type-inference and type-validation.

Returns: LocalHttpRequestHandler<Schema, 'DELETE', Path>

interceptor.head()

Creates a HEAD HttpRequestHandler for a path declared in the interceptor schema.

interceptor.head(path);

Arguments:

  • path: string

    The path to intercept. Paths with dynamic parameters, such as /users/:id, are supported, but you need to specify the original path as a type parameter to get type-inference and type-validation.

Returns: LocalHttpRequestHandler<Schema, 'HEAD', Path>

interceptor.options()

Creates a OPTIONS HttpRequestHandler for a path declared in the interceptor schema.

interceptor.options(path);

Arguments:

  • path: string

    The path to intercept. Paths with dynamic parameters, such as /users/:id, are supported, but you need to specify the original path as a type parameter to get type-inference and type-validation.

Returns: LocalHttpRequestHandler<Schema, 'OPTIONS', Path>

interceptor.checkTimes()

Checks if all handlers created by this interceptor have matched the number of requests declared with handler.times().

If some handler has matched fewer or more requests than expected, this method will throw a TimesCheckError error, including a stack trace to the handler.times() that was not satisfied.

This is useful in an afterEach hook (or equivalent) to make sure that all expected requests were made at the end of each test.

When requestSaving.enabled is true in your interceptor, the TimesCheckError errors will also list each unmatched request with diff of the expected and received data. This is useful for debugging requests that did not match a handler with restrictions.

interceptor.checkTimes();

Returns: void

interceptor.clear()

Clears the interceptor and all of its HttpRequestHandler instances, including their registered responses and intercepted requests.

After calling this method, the interceptor will no longer intercept any requests until new mock responses are registered. This is useful to reset the interceptor mocks between tests.

interceptor.clear();

Returns: void