Skip to content

Commit

Permalink
prettify docs
Browse files Browse the repository at this point in the history
  • Loading branch information
wheresrhys committed Aug 20, 2018
1 parent 03e93fc commit b548744
Show file tree
Hide file tree
Showing 8 changed files with 155 additions and 104 deletions.
129 changes: 75 additions & 54 deletions docs/api.md

Large diffs are not rendered by default.

3 changes: 2 additions & 1 deletion docs/examples.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,4 +6,5 @@
- Examples

# Examples
//todo

//todo
3 changes: 2 additions & 1 deletion docs/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,14 +10,15 @@ As well as shorthand methods for the simplest use cases, it offers a flexible AP
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 v7

- Introduction
- [Quickstart](/fetch-mock/quickstart)
- [Installation and usage ](/fetch-mock/installation)
- [API documentation](/fetch-mock/api)
- [Troubleshooting](/fetch-mock/troubleshooting)
- [Examples](/fetch-mock/examples)

* [V6 - V7 upgrade guide](/fetch-mock/v6-v7-upgrade)
* [V6 docs](/fetch-mock/v6)
* [V5 - V6 upgrade guide](/fetch-mock/v5-v6-upgrade)
Expand Down
25 changes: 15 additions & 10 deletions docs/installation.md
Original file line number Diff line number Diff line change
@@ -1,28 +1,31 @@
- [Introduction](/fetch-mock)
- [Quickstart](/fetch-mock/quickstart)
- Installation and usage
- 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`
- 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.

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.
- 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

Expand All @@ -36,7 +39,8 @@ 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

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')();
Expand All @@ -46,8 +50,9 @@ fetchMock.config = Object.assign(fetchMock.config, {
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)
15 changes: 9 additions & 6 deletions docs/quickstart.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,19 +12,22 @@
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();
});
return fetch('http://httpbin.org/get').then(function(response) {
return response.json();
});
};
```

Expand All @@ -36,10 +39,10 @@ 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'});
fetchMock.get('*', { hello: 'world' });

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

// Unmock.
Expand All @@ -50,5 +53,5 @@ Result:

```bash
$ node mocked.js
'got data' { hello: 'world' }
'got data' { hello: 'world' }
```
23 changes: 13 additions & 10 deletions docs/troubleshooting.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
### `fetch` is assigned to a local variable, not a global

First of all, consider whether you could just use `fetch` as a global. Here are 3 reasons why this is a good idea:

- The `fetch` standard defines it as a global (and in some cases it won't work unless bound to `window`), so to write isomorphic code it's probably best to stick to this pattern
- [`isomorphic-fetch`](https://www.npmjs.com/package/isomorphic-fetch) takes care of installing it as a global in nodejs or the browser, so there's no effort on your part to do so.
- `fetch-mock` is primarily designed to work with `fetch` as a global and your experience of using it will be far more straightforward if you follow this pattern
Expand All @@ -19,19 +20,21 @@ Still not convinced?
In that case `fetchMock.sandbox()` can be used to generate a function which you can pass in to a mock loading library such as [`mockery`](https://www.npmjs.com/package/mockery) instead of `fetch`

### `fetch` doesn't seem to be getting mocked?
* If using a mock loading library such as `mockery`, are you requiring the module you're testing after registering `fetch-mock` with the mock loader? You probably should be ([Example incorrect usage](https://github.com/wheresrhys/fetch-mock/issues/70)). If you're using ES6 `import` it may not be possible to do this without reverting to using `require()` sometimes.
* If using `isomorphic-fetch` in your source, are you assigning it to a `fetch` variable? You *shouldn't* be i.e.
* `import 'isomorphic-fetch'`, not `import fetch from 'isomorphic-fetch'`
* `require('isomorphic-fetch')`, not `const fetch = require('isomorphic-fetch')`

- If using a mock loading library such as `mockery`, are you requiring the module you're testing after registering `fetch-mock` with the mock loader? You probably should be ([Example incorrect usage](https://github.com/wheresrhys/fetch-mock/issues/70)). If you're using ES6 `import` it may not be possible to do this without reverting to using `require()` sometimes.
- If using `isomorphic-fetch` in your source, are you assigning it to a `fetch` variable? You _shouldn't_ be i.e.
- `import 'isomorphic-fetch'`, not `import fetch from 'isomorphic-fetch'`
- `require('isomorphic-fetch')`, not `const fetch = require('isomorphic-fetch')`

### Environment doesn't support requiring fetch-mock?
* 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-browserified.js` in a script tag. This loads fetch-mock into the `fetchMock` global variable.
* For server side tests running in nodejs 0.12 or lower use `require('fetch-mock/es5/server')`

- 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-browserified.js` in a script tag. This loads fetch-mock into the `fetchMock` global variable.
- For server side tests running in nodejs 0.12 or lower use `require('fetch-mock/es5/server')`

### Matching `Request` objects in node fails
In node, if using npm at a version less than 2 the `Request` constructor used by `fetch-mock` won't necessarily be the same as the one used by `node-fetch`. To fix this either:
* upgrade to npm@3
* use `fetchMock.config.Request = myRequest`, where `myRequest` is a reference to the Request constructor used in your application code.

In node, if using npm at a version less than 2 the `Request` constructor used by `fetch-mock` won't necessarily be the same as the one used by `node-fetch`. To fix this either:

- upgrade to npm@3
- use `fetchMock.config.Request = myRequest`, where `myRequest` is a reference to the Request constructor used in your application code.
16 changes: 10 additions & 6 deletions docs/v5-v6-upgrade.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,28 +7,32 @@ For the most common use cases, and the basic mocking and inspecting api, very li
# Changes

## Configuration and installation

- Requires `async / await` - for older node versions use v5, or require the transpiled version: `require('fetch-mock/es5/server')`
- *No change to mocking fetch as a global*
- _No change to mocking fetch as a global_
- Uses whatever version of `node-fetch` you have already installed in your project i.e. can be used with `node-fetch` 2
- `.sandbox()` no longer accepts a custom `Promise` implementation as a parameter
- Sandboxes can now be 'sub-classed' i.e. define some mocks on a sandbox, then call `.sandbox()` on it to create a new one inheriting all its settings
- No longer has a `setImplementations()` method. Instead, assign custom `Promise` and `fetch` helper classes directly to the `config` property of the fetch-mock instance. This may be done before or after sandboxing
- No longer has a `setImplementations()` method. Instead, assign custom `Promise` and `fetch` helper classes directly to the `config` property of the fetch-mock instance. This may be done before or after sandboxing
- No longer has a `configure()` method. Instead set options directly on the `.config` property. See the api docs for a complete list of options

## Routing

- `^` is no longer a valid way of matching the beginning of strings; use `begin:` instead
- `overwriteRoutes` option allows for existing routes in a mock to be overwritten. It's also possible to define multiple routes with 'the same' matcher. Default behaviour is to error. Set to `false` to use old "buffer-like" behavior

## Responses

- `Content-Length` header generated by default for all responses (can be configured to not do so globally or per response.)
- Objects will be converted to `JSON` responses if they contain any properties not listed in the docs as special response config options (previous behaviour was to convert if any of the properties were present). This means that e.g. `{user: 'me', status: 'happy'}` can easily be sent as `JSON`
- `__redirectUrl` option is now named `redirectUrl`
- `times` option is now named `repeat`

## Inspecting

- All inspection methods now filter, in addition to the existing check against `matcher.toString()`, based on the following rules
+ An exact url
+ `true` for matched calls only
+ `false` for unmatched calls only
+ `undefined` (or no argument) includes all calls to `fetch` in order in a single array, i.e. no longer an object with `matched` and `unmatched` properties
- An exact url
- `true` for matched calls only
- `false` for unmatched calls only
- `undefined` (or no argument) includes all calls to `fetch` in order in a single array, i.e. no longer an object with `matched` and `unmatched` properties
- When `fetch` was last called with a `Request` object, `lastUrl()` and `lastOpts()` give easier access to the `url` and full `Request` object
Loading

0 comments on commit b548744

Please sign in to comment.