Skip to content

Commit

Permalink
relint docs
Browse files Browse the repository at this point in the history
  • Loading branch information
wheresrhys committed Aug 20, 2018
1 parent 4f41234 commit 26e9d1e
Show file tree
Hide file tree
Showing 3 changed files with 89 additions and 64 deletions.
90 changes: 48 additions & 42 deletions docs/api.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,43 +15,46 @@
## Mocking calls to `fetch`

#### `mock(matcher, response, options)` or `mock(options)`
Replaces `fetch` with a stub which records its calls, grouped by route, and optionally returns a mocked `Response` object or passes the call through to `fetch()`. Calls to `.mock()` can be chained. *Note that once mocked, `fetch` will error on any unmatched calls. Use `.spy()` or `.catch()` to handle unmocked calls more gracefully*
* `matcher`: Condition for selecting which requests to mock. (For matching based on headers, query strings or other `fetch` options see the `options` parameter documented below). Accepts any of the following:
* `string`: Either
* an exact url to match e.g. 'http://www.site.com/page.html'
* `*` to match any url
* `begin:http://www.site.com/` to match urls beginning with a string
* `end:.jpg` to match urls ending with a string
* `path:/posts/2018/7/3` to match urls with a given path
* `glob:http://*.*` to match glob patterns
* `express:/user/:user` to match [express style paths](https://www.npmjs.com/package/path-to-regexp)
* `RegExp`: A regular expression to test the url against
* `Function(url, opts)`: A function (returning a Boolean) that is passed the url and opts `fetch()` is called with (or, if `fetch()` was called with one, the `Request` instance)

Replaces `fetch` with a stub which records its calls, grouped by route, and optionally returns a mocked `Response` object or passes the call through to `fetch()`. Calls to `.mock()` can be chained. _Note that once mocked, `fetch` will error on any unmatched calls. Use `.spy()` or `.catch()` to handle unmocked calls more gracefully_

- `matcher`: Condition for selecting which requests to mock. (For matching based on headers, query strings or other `fetch` options see the `options` parameter documented below). Accepts any of the following:
- `string`: Either
- an exact url to match e.g. 'http://www.site.com/page.html'
- `*` to match any url
- `begin:http://www.site.com/` to match urls beginning with a string
- `end:.jpg` to match urls ending with a string
- `path:/posts/2018/7/3` to match urls with a given path
- `glob:http://*.*` to match glob patterns
- `express:/user/:user` to match [express style paths](https://www.npmjs.com/package/path-to-regexp)
- `RegExp`: A regular expression to test the url against
- `Function(url, opts)`: A function (returning a Boolean) that is passed the url and opts `fetch()` is called with (or, if `fetch()` was called with one, the `Request` instance)

_Note that if using `end:` or an exact url matcher, `fetch-mock` ([for good reason](https://url.spec.whatwg.org/#url-equivalence)) is unable to distinguish whether URLs without a path end in a trailing slash or not i.e. `http://thing` is treated the same as `http://thing/`_
* `response`: Configures the http response returned by the mock. Can take any of the following values (or be a `Promise` for any of them, enabling full control when testing race conditions etc.)
* `Response`: A `Response` instance - will be used unaltered
* `number`: Creates a response with this status
* `string`: Creates a 200 response with the string as the response body
* `configObject` If an object _does not contain_ any properties aside from those listed below it is treated as config to build a `Response`
* `body`: Set the response body (`string` or `object`)
* `status`: Set the response status (default `200`)
* `headers`: Set the response headers. (`object`)
* `throws`: If this property is present then fetch returns a `Promise` rejected with the value of `throws`
* `sendAsJson`: This property determines whether or not the request body should be converted to `JSON` before being sent (defaults to `true`).
* `includeContentLength`: Set this property to true to automatically add the `content-length` header (defaults to `true`).
* `redirectUrl`: *experimental* the url the response should be from (to imitate followed redirects - will set `redirected: true` on the response)
* `object`: All objects that do not meet the criteria above are converted to `JSON` and returned as the body of a 200 response.
* `Function(url, opts)`: A function that is passed the url and opts `fetch()` is called with and that returns any of the responses listed above (or a `Promise` for any of them)
* `options`: A configuration object with all/additional properties to define a route to mock
* `name`: A unique string naming the route. Used to subsequently retrieve references to the calls, grouped by name. Defaults to `matcher.toString()`
* `method`: http method to match
* `headers`: key/value map of headers to match
* `query`: key/value map of query strings to match, in any order
* `matcher`: as specified above
* `response`: as specified above
* `repeat`: An integer, `n`, limiting the number of times the matcher can be used. If the route has already been called `n` times the route will be ignored and the call to `fetch()` will fall through to be handled by any other routes defined (which may eventually result in an error if nothing matches it)
* `overwriteRoutes`: If the route you're adding clashes with an existing route, setting `true` here will overwrite the clashing route, `false` will add another route to the stack which will be used as a fallback (useful when using the `repeat` option). Adding a clashing route without specifying this option will throw an error. It can also be set as a global option (see the **Config** section below)

- `response`: Configures the http response returned by the mock. Can take any of the following values (or be a `Promise` for any of them, enabling full control when testing race conditions etc.)
- `Response`: A `Response` instance - will be used unaltered
- `number`: Creates a response with this status
- `string`: Creates a 200 response with the string as the response body
- `configObject` If an object _does not contain_ any properties aside from those listed below it is treated as config to build a `Response`
- `body`: Set the response body (`string` or `object`)
- `status`: Set the response status (default `200`)
- `headers`: Set the response headers. (`object`)
- `throws`: If this property is present then fetch returns a `Promise` rejected with the value of `throws`
- `sendAsJson`: This property determines whether or not the request body should be converted to `JSON` before being sent (defaults to `true`).
- `includeContentLength`: Set this property to true to automatically add the `content-length` header (defaults to `true`).
- `redirectUrl`: _experimental_ the url the response should be from (to imitate followed redirects - will set `redirected: true` on the response)
- `object`: All objects that do not meet the criteria above are converted to `JSON` and returned as the body of a 200 response.
- `Function(url, opts)`: A function that is passed the url and opts `fetch()` is called with and that returns any of the responses listed above (or a `Promise` for any of them)
- `options`: A configuration object with all/additional properties to define a route to mock
- `name`: A unique string naming the route. Used to subsequently retrieve references to the calls, grouped by name. Defaults to `matcher.toString()`
- `method`: http method to match
- `headers`: key/value map of headers to match
- `query`: key/value map of query strings to match, in any order
- `matcher`: as specified above
- `response`: as specified above
- `repeat`: An integer, `n`, limiting the number of times the matcher can be used. If the route has already been called `n` times the route will be ignored and the call to `fetch()` will fall through to be handled by any other routes defined (which may eventually result in an error if nothing matches it)
- `overwriteRoutes`: If the route you're adding clashes with an existing route, setting `true` here will overwrite the clashing route, `false` will add another route to the stack which will be used as a fallback (useful when using the `repeat` option). Adding a clashing route without specifying this option will throw an error. It can also be set as a global option (see the **Config** section below)

#### `sandbox()`

Expand Down Expand Up @@ -104,15 +107,16 @@ _Note that `restore()` and `reset()` are both bound to fetchMock, and can be use
## Inspecting how `fetch()` has been called

### Filtering

Most of the methods below accept two parameters, `(filter, options)`
- `filter` Enables filtering fetch calls for the most commonly use cases. The behaviour can be counterintuitive. The following rules, applied in the order they are described, are used to try to retrieve calls. If any rule retrieves no calls the next rule will be tried.
- If `filter` is `undefined` all calls, matched _and_ unmatched, are returned
- If `filter` is `true` (or `fetchMock.MATCHED`) all calls that matched some route are returned
- If `filter` is `false` (or `fetchMock.UNMATCHED`) all calls that did not match any route are returned (when `.spy()`, `catch()` or `config.fallThroughToNetwork` were used to prevent errors being thrown)
- If `filter` is the name of a named route, all calls handled by that route are returned
- If `filter` is equal to `matcher` or `matcher.toString()` for a route, all calls handled by that route are returned
- `filter` is executed using the same execution plan as matchers used in `.mock()`. Any calls matched by it will be returned. If `options` is also passed this is used in a similar way to the options used by `mock()`. Alternatively, `options` can be a string specifying a `method` to filter by

- `filter` Enables filtering fetch calls for the most commonly use cases. The behaviour can be counterintuitive. The following rules, applied in the order they are described, are used to try to retrieve calls. If any rule retrieves no calls the next rule will be tried.
- If `filter` is `undefined` all calls, matched _and_ unmatched, are returned
- If `filter` is `true` (or `fetchMock.MATCHED`) all calls that matched some route are returned
- If `filter` is `false` (or `fetchMock.UNMATCHED`) all calls that did not match any route are returned (when `.spy()`, `catch()` or `config.fallThroughToNetwork` were used to prevent errors being thrown)
- If `filter` is the name of a named route, all calls handled by that route are returned
- If `filter` is equal to `matcher` or `matcher.toString()` for a route, all calls handled by that route are returned
- `filter` is executed using the same execution plan as matchers used in `.mock()`. Any calls matched by it will be returned. If `options` is also passed this is used in a similar way to the options used by `mock()`. Alternatively, `options` can be a string specifying a `method` to filter by

#### `called(filter, method)`

Expand All @@ -135,9 +139,11 @@ Returns the arguments for the last matched call to fetch
Returns the url for the last matched call to fetch. When `fetch` was last called using a `Request` instance, the url will be extracted from this

#### `lastOptions(filter, method)`

Returns the options for the last matched call to fetch. When `fetch` was last called using a `Request` instance, a set of `options` inferred from the `Request` will be returned

#### `flush()`

Returns a `Promise` that resolves once all fetches handled by fetch-mock have resolved. Pass in `true` to wait for all response methods (`res.json()`, `res.text()`, etc.) to resolve too. Useful for testing code that uses `fetch` but doesn't return a promise.

## Config
Expand Down
7 changes: 4 additions & 3 deletions docs/installation.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,19 +20,20 @@ const fetchMock = require('fetch-mock');
const { fetchMock, MATCHED, UNMATCHED } = require('fetch-mock');
```


Some exceptions include:

- If your client-side code or tests do not use a loader that respects the browser field of `package.json` use `require('fetch-mock/es5/client')`.
- If you need to use fetch-mock without commonjs, you can include the precompiled `node_modules/fetch-mock/es5/client-bundle.js` in a script tag. This loads fetch-mock into the `fetchMock` global variable.
- For server side tests running in nodejs 6 or lower use `require('fetch-mock/es5/server')`. You will also need to `npm i -D babel-polyfill`

## Global fetch

<<<<<<< HEAD

=======
>>>>>>> 315bf4bee040aa243eaf3b2a418741d35444bccb
By default fetch-mock assumes `fetch` is a global so once you've required fetch-mock refer to the quickstart and api docs.

> > > > > > > 315bf4bee040aa243eaf3b2a418741d35444bccb
> > > > > > > By default fetch-mock assumes `fetch` is a global so once you've required fetch-mock refer to the quickstart and api docs.
### Polyfilling fetch

Expand Down
Loading

0 comments on commit 26e9d1e

Please sign in to comment.