forked from mswjs/mswjs.io
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
feef1cc
commit ff10d9f
Showing
44 changed files
with
3,185 additions
and
110 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,52 @@ | ||
--- | ||
title: composeMocks() | ||
--- | ||
|
||
A function that composes the given request handlers into a single mocking schema. Any intercepted request is matched against that schema and the first successful match is used to mock the request. | ||
|
||
## Type Definition | ||
|
||
```ts | ||
type ComposeMocks = ( | ||
...requetsHandlers: RequestHandler[] | ||
): SchemaAPI | ||
|
||
type SchemaAPI = { | ||
// Starts a Mock Service Worker | ||
start: ( | ||
// A custom path to the Service Worker | ||
serviceWorkerUrl?: string, | ||
// Service Worker registration options | ||
registrationOptions?: RegistrationOptions | ||
) => void | ||
|
||
// Stop a running Mock Service Worker | ||
stop: () => void | ||
} | ||
``` | ||
## Examples | ||
```js | ||
import { composeMocks, rest } from 'msw' | ||
|
||
const { start } = composeMocks( | ||
rest.get('*/user/:userId', (req, res, ctx) => { | ||
return res( | ||
ctx.json({ | ||
firstName: 'John', | ||
lastName: 'Maverick', | ||
}), | ||
) | ||
}), | ||
) | ||
|
||
// Start the Mock Service Worker | ||
start() | ||
``` | ||
|
||
> Example above uses the standard `rest` namespace forREST API handling. You can, however, create your custom request handlers. | ||
You can provide a custom Service Worker URL as an argument to the start() function. Please see this recipe for more detailed instructions: | ||
|
||
> TODO |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,104 @@ | ||
--- | ||
title: graphql | ||
--- | ||
|
||
The `graphql` namespace is designed for handling GraphQL operations. It contains a set of useful methods for mocking GraphQL requests. | ||
|
||
## Methods | ||
|
||
Each method in this namespace represents a GraphQL _operation kind_: | ||
|
||
- `graphql.query()` | ||
- `graphql.mutation()` | ||
|
||
> Please note that subscriptions are not currently supported. | ||
Using a method under this namespace automatically creates a request handler for the respective GraphQL operation. Pass the operation name as the first argument and the [Response resolver](TODO) as the second. | ||
|
||
```js | ||
import { graphql } from 'msw' | ||
|
||
graphql.query('QueryName', responseResolver) | ||
graphql.mutation('MutationName', responseResolver) | ||
``` | ||
|
||
## Examples | ||
|
||
### Basic query/mutation | ||
|
||
```js | ||
import { composeMocks, graphql } from 'msw' | ||
|
||
const { start } = composeMocks( | ||
graphql.query('GetUserDetail', (req, res, ctx) => { | ||
return res( | ||
ctx.data({ | ||
user: { | ||
firstName: 'John', | ||
lastName: 'Maverick', | ||
}, | ||
}), | ||
) | ||
}), | ||
) | ||
|
||
start() | ||
``` | ||
|
||
### Accessing variables | ||
|
||
The variables of a query/mutation can be accessed in the `req.variables` object. | ||
|
||
```js | ||
import { composeMocks, graphql } from 'msw' | ||
|
||
const { start } = composeMocks( | ||
graphql.mutation('DeletePost', (req, res, ctx) => { | ||
// The post ID to delete | ||
const { postId } = req.variables | ||
|
||
return res(ctx.data([{ id: 2 }, { id: 3 }])) | ||
}), | ||
) | ||
|
||
start() | ||
``` | ||
|
||
### Usage with TypeScript | ||
|
||
```ts | ||
import { composeMocks, graphql } from 'msw' | ||
|
||
// Provide the manually written GraphQL types | ||
// or use the one generated for you (i.e. with "graphql-codegen"). | ||
interface GetUserDetailQuery { | ||
user { | ||
firstName: string | ||
lastName: string | ||
} | ||
} | ||
|
||
interface GetUserDetailQueryVariables { | ||
userId: string | ||
} | ||
|
||
const { start } = composeMocks( | ||
graphql.query<GetUserDetailQuery, GetUserDetailVariables>( | ||
'GetUserDetail', | ||
(req, res, ctx) => { | ||
const { userId } = req.variables | ||
|
||
return res( | ||
ctx.data({ | ||
user: { | ||
firstName: 'John', | ||
lastName: 'Maverick' | ||
} | ||
}) | ||
) | ||
}) | ||
) | ||
) | ||
|
||
start() | ||
``` |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,52 @@ | ||
--- | ||
title: rest | ||
--- | ||
|
||
The `rest` namepsace is designed for a more convenient handling of REST API requests. It contains a set of utility functions for easier mocking of requests that follow REST API specification. | ||
|
||
## Methods | ||
|
||
Each method in this namespace corresponds to a REST API request method. | ||
|
||
- `rest.get()` | ||
- `rest.post()` | ||
- `rest.put()` | ||
- `rest.patch()` | ||
- `rest.delete()` | ||
- `rest.options()` | ||
|
||
Using a method under this namespace automatically creates a request handler that matches any requests with the respective REST API method. Additionally, such request handler accepts a request URL as the first parameter to narrow the match. | ||
|
||
```js | ||
import { rest } from 'msw' | ||
|
||
// Match all "POST" requests to the given path | ||
rest.post('/author/:authorId/:postId', responseResolver) | ||
``` | ||
|
||
Example usage above would match the following requests: | ||
|
||
- `POST /author/1/2` | ||
- `POST /author/123-abc/456-def` | ||
|
||
## Examples | ||
|
||
```js | ||
import { composeMocks, rest } from 'msw' | ||
|
||
const { start } = composeMocks( | ||
rest.get('/users/:userId', (req, res, ctx) => { | ||
const { userId } = req.params | ||
|
||
return res( | ||
ctx.json({ | ||
id: userId, | ||
firstName: 'John', | ||
lastName: 'Maverick', | ||
}), | ||
) | ||
}), | ||
) | ||
|
||
start() | ||
``` |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,73 @@ | ||
--- | ||
title: Path matching | ||
--- | ||
|
||
In order to determine which outgoing requests should be mocked, MSW performs request path matching. It's a process when an actual request is compared to the request handlers you've defined when called `composeMocks()` function. | ||
|
||
> Path matching is relevant only when mocking a REST API. In case of GraphQL, the predicate is defined by the _operation name_. Learn more about how Mock Service Worker matches GraphQL requests in the [GraphQL API section](/docs/api/graphql). | ||
By default, an outgoing request will be mocked if there is a corresponding request handler that: | ||
|
||
- Has the same method; | ||
- Has a matching URL. | ||
|
||
## URL matching | ||
|
||
It is possible to perform a request's URL matching in three ways: | ||
|
||
- Exact URL string; | ||
- Path; | ||
- RegExp. | ||
|
||
> URL query parameters and hash **are ignored** when matching request URL. It's recommended to omit them when specifying URL or paths in request handlers. | ||
## Exacy URL string | ||
|
||
Using an exact URL string for the request handler path would match all requests which URL equals to that string. | ||
|
||
```js | ||
import { rest } from 'msw' | ||
|
||
rest.post('https://api.backend.com/users', responseResolver) | ||
``` | ||
|
||
> Only the POST request to `https://api.backend.dev/users` would match this request handler. | ||
## Path | ||
|
||
Similar to how route paths are declared in Express, MSW supports path format for request handlers. Using path allows you to have wildcards and parameters in your URL. | ||
|
||
### Patch with wildcard | ||
|
||
```js | ||
import { rest } from 'msw' | ||
|
||
rest.get('/users/*', responseResolver) | ||
``` | ||
|
||
### Path with parameters | ||
|
||
To add a parameter to your request path use the `:paramName` format. | ||
|
||
```js | ||
import { rest } from 'msw' | ||
|
||
rest.post('https://api.backend.dev/user/:userId', (req, res, ctx) => { | ||
const { userId } = req.params | ||
// resolve the response... | ||
}) | ||
``` | ||
|
||
You can then access the declared parameters in the `req.params` object. For example, if the application performs a POST request to `https://api.backend.dev/user/abc-123`, then `req.params.userId` would equal to `"abc-123"`. | ||
|
||
## RegExp | ||
|
||
When provided a regular expression, MSW would only mock the requests which URL matches that regular expression. Unmatched requests would be performed as-is. | ||
|
||
```js | ||
import { rest } from 'msw' | ||
|
||
rest.delete(/\/posts\//, responseResolver) | ||
``` | ||
|
||
Performing a DELETE request to `http://localhost:8080/posts/` will match this request handler. The hostname of the URL matters not in this case, as this regular expression matches a portion of the URL. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,29 @@ | ||
--- | ||
title: Request handler | ||
--- | ||
|
||
**Request handler** is a function that determines whether an outgoing request should be mocked, and specifies its mocked response. | ||
|
||
Request handler function returns an Object with the following properties: | ||
|
||
| Property name | Type | Description | | ||
| --------------- | --------------------------------- | --------------------------------------------------------------------------------------------------------------------- | | ||
| `mask` | `string` | Request URL path used to extract path parameters from the URL. | | ||
| `predicate` | `(req: MockedRequest) => boolean` | Predicate function that determines whether a request should be mocked using the given request handler. | | ||
| `resolver` | (req, res, ctx) => MockedResponse | [Response resolver](/docs/basics/response-resolver) function that returns the mocked response. | | ||
| `defineContext` | ... | Custom context definition function. Determines which [Context utilities](TODO) are available in this request handler. | | ||
|
||
## Type definition | ||
|
||
> TODO Add the ref to ts | ||
## Standard handlers | ||
|
||
Mock Service Worker exposes a set of standard request handlers for your convenience. It's recommende to use those, as they are sufficient in most use cases. | ||
|
||
**See the list of the standard request handlers below:** | ||
|
||
- [rest](/docs/api/rest) | ||
- [graphql](/docs/api/graphql) | ||
|
||
> You can always create a [Custom request handler](/docs/recipes/custom-request-handler) when the standard ones are not enough. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,33 @@ | ||
--- | ||
title: Response resolver | ||
--- | ||
|
||
**Response resolver** is a function that accepts a matched outgoing request and returns a mocked response. | ||
|
||
## Type definition | ||
|
||
> TODO Add the ref to ts | ||
## Parameters | ||
|
||
Response resolver function accepts the following parameters: | ||
|
||
- [`request`](/docs/basics/response-resolver/request) | ||
- [`response`](/docs/basics/response-resolver/response) | ||
- [`context`](/docs/basics/response-resolver/context) | ||
|
||
## Examples | ||
|
||
```js | ||
export const mockUserData = (req, res, ctx) => { | ||
const { usedId } = req.params | ||
|
||
return res( | ||
ctx.json({ | ||
firstName: 'John', | ||
lastName: 'Maverick', | ||
age: 38, | ||
}), | ||
) | ||
} | ||
``` |
Oops, something went wrong.