Skip to content

Commit

Permalink
include old docs
Browse files Browse the repository at this point in the history
  • Loading branch information
wheresrhys committed Aug 20, 2018
1 parent d470304 commit 03e93fc
Show file tree
Hide file tree
Showing 8 changed files with 352 additions and 0 deletions.
4 changes: 4 additions & 0 deletions docs/v6/_config.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
markdown: kramdown
theme: jekyll-theme-slate
title: fetch-mock
description: Mock http requests made using fetch
138 changes: 138 additions & 0 deletions docs/v6/api.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,138 @@
- [Introduction](/fetch-mock)
- [Quickstart](/fetch-mock/quickstart)
- [Installation and usage](/fetch-mock/installation)
- API documentation
- [Troubleshooting](/fetch-mock/troubleshooting)
- [Examples](/fetch-mock/examples)

# API Documentation

* [V5 - V6 upgrade guide](/fetch-mock/v5-v6-upgrade)
* [V5 docs](/fetch-mock/v5)

## 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
* `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)

* `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 a the value of `throws` is thrown
* `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()`
This returns a drop-in mock for fetch which can be passed to other mocking libraries. It implements the full fetch-mock api and maintains its own state independent of other instances, so tests can be run in parallel. e.g.

#### `once()`
Shorthand for `mock()` which limits to being called one time only. (see `repeat` option above)

#### `get()`, `post()`, `put()`, `delete()`, `head()`, `patch()`
Shorthands for `mock()` restricted to a particular method *Tip: if you use some other method a lot you can easily define your own shorthands e.g.:*

```
fetchMock.purge = function (matcher, response, options) {
return this.mock(matcher, response, Object.assign({}, options, {method: 'PURGE'}));
}
```

#### `getOnce()`, `postOnce()`, `putOnce()`, `deleteOnce()`, `headOnce()`, `patchOnce()`
Shorthands for `mock()` restricted to a particular method and that will only respond once

#### `catch(response)`
This is used to define how to respond to calls to fetch that don't match any of the defined mocks. It accepts the same types of response as a normal call to `.mock()`. It can also take an arbitrary function to completely customise behaviour of unmatched calls. It is chainable and can be called before or after other calls to `.mock()`. If `.catch() ` is called without any parameters then every unmatched call will receive a `200` response

#### `spy()`
Similar to `catch()`, this records the call history of unmatched calls, but instead of responding with a stubbed response, the request is passed through to native `fetch()` and is allowed to communicate over the network.

To use `.spy()` on a sandboxed `fetchMock`, `fetchMock.config.fetch` must be set to a reference to the `fetch` implementation you use in your code.

```
fetchMock.sandbox().mock('http://domain.com', 200)
```
Existing sandboxed `fetchMock`s can also have `.sandbox()` called on them, thus building mocks that inherit some settings from a parent mock

#### `restore()`
Chainable method that restores `fetch()` to its unstubbed state and clears all data recorded for its calls.

#### `reset()`
Chainable method that clears all data recorded for `fetch()`'s calls. *It will not restore fetch to its default implementation*

*Note that `restore()` and `reset()` are both bound to fetchMock, and can be used directly as callbacks e.g. `afterEach(fetchMock.restore)` will work just fine. There is no need for `afterEach(function () {fetchMock.restore()})`*

## Inspecting how `fetch()` has been called

### Filtering
Most of the methods below accept two parameters, `(filter, method)`
- `filter` Enables filtering fetch calls for the most commonly use cases. It can be:
- the name of a route
- The value of `matcher` or `matcher.toString()` for any unnamed route. You _can_ pass in the original regex or function as a matcher, but they will be converted to strings and used to look up values in fetch-mock's internal maps of calls, _not_ used as regexes or functions executed on teh url
- If `filter` is a string, and it does not match any routes, it is asumed the string is a url, and calls to `fetch` made with that url are returned
- `true` for matched calls only
- `false` for unmatched calls only
- `undefined` for all calls to fetch
- `method` A http method to filter by

#### `called(filter, method)`
Returns a Boolean indicating whether fetch was called and a route was matched. If `filter` is specified it only returns `true` if that particular route was matched.

#### `done(filter, method)`
Returns a Boolean indicating whether fetch was called the expected number of times (or at least once if the route defines no expectation is set for the route). _Unlike the other methods for inspecting calls, unmatched calls are irrelevant_. Therefore, if no `filter` is passed, `done()` returns `true` if every route has been called the number of expected times.

#### `calls(filter, method)`
Returns an array of all calls to fetch matchingthe given filters. Each call is returned as an array of length 2.

#### `lastCall(filter, method)`
Returns the arguments for the last matched call to fetch

#### `lastUrl(filter, method)`
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, the entire `Request` instance will be returned

#### `flush()`
Returns a `Promise` that resolves once all fetches handled by fetch-mock have resolved. Useful for testing code that uses `fetch` but doesn't return a promise.

## Config

On either the global or sandboxed `fetchMock` instances, the following config options can be set by setting properties on `fetchMock.config`. Many can also be set on individual calls to `.mock()`.
* `sendAsJson` [default `true`] - by default fetchMock will convert objects to JSON before sending. This is overrideable from each call but for some scenarios e.g. when dealing with a lot of array buffers, it can be useful to default to `false`
* `includeContentLength` [default `true`]: When set to true this will make fetchMock automatically add the `content-length` header. This is especially useful when combined with `sendAsJson` because then fetchMock does the conversion to JSON for you and knows the resulting length so you don’t have to compute this yourself by basically doing the same conversion to JSON.
* `fallbackToNetwork` [default `false`] If true then unmatched calls will transparently fall through to the network, if false an error will be thrown. If set to `always`, all calls will fall through, effectively disabling fetch-mock. to Within individual tests `.catch()` and `spy()` can be used for fine-grained control of this
* `overwriteRoutes`: If a new route 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.
* `warnOnFallback` [default `true`] If true then any unmatched calls that are caught by a fallback handler (either the network or a custom function set using `catch()`) will emit warnings
* `Headers`,`Request`,`Response`,`Promise`, `fetch`
When using non standard fetch (e.g. a ponyfill, or aversion of `node-fetch` other than the one bundled with `fetch-mock`) or an alternative Promise implementation, this will configure fetch-mock to use your chosen implementations.

Note that `Object.assign(fetchMock.config, require('fetch-ponyfill')())` will configure fetch-mock to use all of fetch-ponyfill's classes. In most cases, it should only be necessary to set this once before any tests run.

9 changes: 9 additions & 0 deletions docs/v6/examples.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
- [Introduction](/fetch-mock)
- [Quickstart](/fetch-mock/quickstart)
- [Installation and usage ](/fetch-mock/installation)
- [API documentation](/fetch-mock/api)
- [Troubleshooting](/fetch-mock/troubleshooting)
- Examples

# Examples
//todo
23 changes: 23 additions & 0 deletions docs/v6/index.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
fetch-mock allows mocking http requests made using fetch, or any one of the many libraries imitating its api such as [isomorphic-fetch](https://www.npmjs.com/package/isomorphic-fetch), [node-fetch](https://www.npmjs.com/package/node-fetch) and [fetch-ponyfill](https://www.npmjs.com/package/fetch-ponyfill).

The library will run in most JavaScript environments, including nodejs, web workers and service workers, and any browser that either supports fetch natively or that can have a fetch polyfill/ponyfill installed.

As well as shorthand methods for the simplest use cases, it offers a flexible API for customising all aspects of mocking behaviour.

**Uses `async / await` - for older node versions use v5, or require the transpiled version: require('fetch-mock/es5/server')**

<div style="padding: 10px; border: 4px dashed; font-size: 1.2em;">
I devote a lot of time to maintaining fetch-mock for free. I don't ask for payment, but am raising money for a refugee charity - <a href="https://www.justgiving.com/fundraising/rhys-evans-walk">please consider donating</a>
</div>


## These docs are for v6

- [v5 docs](/fetch-mock/v5)
- [V5 - V6 upgrade guide](/fetch-mock/v5-v6-upgrade)
- Introduction
- [Quickstart](/fetch-mock/quickstart)
- [Installation and usage ](/fetch-mock/installation)
- [API documentation](/fetch-mock/api)
- [Troubleshooting](/fetch-mock/troubleshooting)
- [Examples](/fetch-mock/examples)
53 changes: 53 additions & 0 deletions docs/v6/installation.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
- [Introduction](/fetch-mock)
- [Quickstart](/fetch-mock/quickstart)
- Installation and usage
- [API documentation](/fetch-mock/api)
- [Troubleshooting](/fetch-mock/troubleshooting)
- [Examples](/fetch-mock/examples)

# Installation
Install fetch-mock using `npm install --save-dev fetch-mock`

In most environments use `const fetchMock = require('fetch-mock')` to use it in your code. 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
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
Many older browsers will require polyfilling the `fetch` global

* In nodejs `require('isomorphic-fetch')` before any of your tests.
* In the browser `require('isomorphic-fetch')` can also be used, but it may be easier to `npm install whatwg-fetch` (the module isomorphic-fetch is built around) and load `./node_modules/whatwg-fetch/fetch.js` directly into the page, either in a script tag or by referencing in your test runner config.
* When using karma-webpack it's best not to use the `webpack.ProvidePlugin` for this. Instead just add `node_modules/whatwg-fetch/fetch.js` to your list of files to include, or require it directly into your tests before requiring fetch-mock.

## Non-global fetch

When using a non-global fetch implementation (such as node-fetch or fetch-ponyfill) use the `sandbox()` method to return a function that can be used as a replacement for fetch, and be passed into your source code using your choice of mocking library. The function returned by `sandbox()` supports the full fetch-mock api so once generated it can be worked with as if it were the original `fetch-mock` object, e.g.

```
const fetchMock = require('fetch-mock');
const myMock = fetchMock.sandbox().mock('/home', 200);
// pass myMock in to your application code, instead of fetch, run it, then...
expect(myMock.called('/home')).to.be.true;
```

## References to Request, Response, Headers, fetch and Promise
If you're using a non-global fetch implementation, or wish to use a custom Promise implementation, you may need to tell fetch-mock to use these when matching requests and returning responses. Do this by setting these properties on `fetchMock.config`, e.g

```
const ponyfill = require('fetch-ponyfill')();
fetchMock.config = Object.assign(fetchMock.config, {
Promise: require('Bluebird').promise,
Headers: ponyfill.Headers,
Request: ponyfill.Request,
Response: ponyfill.Response
fetch: ponyfill
},
```
This should be done before running any tests.

Note that when using `node-fetch`, `fetch-mock` will use the instance you already have installed so there should be no need to set any of the above (apart from `fetch`, which is required if you intend to use the `.spy()` method)
54 changes: 54 additions & 0 deletions docs/v6/quickstart.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
- [Introduction](/fetch-mock)
- Quickstart
- [Installation and usage ](/fetch-mock/installation)
- [API documentation](/fetch-mock/api)
- [Troubleshooting](/fetch-mock/troubleshooting)
- [Examples](/fetch-mock/examples)

# Quickstart

## Setting up your mock

The commonest use case is `fetchMock.mock(matcher, response)`, where `matcher` is a string or regex to match and `response` is a statusCode, string or object literal. You can also use `fetchMock.once(url ...)` to limit to a single call or `fetchMock.get()`, `fetchMock.post()` etc. to limit to a method. All these methods are chainable so you can easily define several mocks in a single test.

## Analysing calls to your mock
`fetchMock.called(matcher)` reports if any calls matched your mock (or leave `matcher` out if you just want to check `fetch` was called at all). `fetchMock.lastCall()`, `fetchMock.lastUrl()` or `fetchMock.lastOptions()` give you access to the parameters last passed in to `fetch`. `fetchMock.done()` will tell you if `fetch` was called the expected number of times.

## Tearing down your mock
`fetchMock.reset()` resets the call history. `fetchMock.restore()` will also restore `fetch()` to its native implementation

## Example
Example with node: suppose we have a file `make-request.js` with a function that calls `fetch`:

```js
module.exports = function makeRequest() {
return fetch("http://httpbin.org/get").then(function(response) {
return response.json();
});
};
```

We can use fetch-mock to mock `fetch`. In `mocked.js`:

```js
var fetchMock = require('fetch-mock');
var makeRequest = require('./make-request');

// Mock the fetch() global to always return the same value for GET
// requests to all URLs.
fetchMock.get('*', {hello: 'world'});

makeRequest().then(function(data) {
console.log('got data', data);
});

// Unmock.
fetchMock.restore();
```

Result:

```bash
$ node mocked.js
'got data' { hello: 'world' }
```
Loading

0 comments on commit 03e93fc

Please sign in to comment.