Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Rhys/fm 12 docs #846

Draft
wants to merge 20 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
20 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 0 additions & 32 deletions docs/docs/@fetch-mock/core/index.md

This file was deleted.

7 changes: 0 additions & 7 deletions docs/docs/@fetch-mock/index.md

This file was deleted.

6 changes: 0 additions & 6 deletions docs/docs/@fetch-mock/vitest/index.md

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ An options object compatible with the [route api](#api-mockingmock_options) to b

`fetchMock.callHistory` exposes the following methods.

> Note that fetch calls made using `(url, options)` pairs are added synchronously, but calls using a `Request` are added asynchronously. This is because when a `Request` is used access to many of its internals is via asynchronous methods, while for an options object they can be read directly. In general it's best to `await` your code to complete before attempting to access call history.
> Note that fetch calls made using `(url, options)` pairs are added synchronously, but calls using a `Request` are added asynchronously. This is because when a `Request` is used access to many of its internals is via asynchronous methods, while for an options object they can be read directly. In general it's best to `await` your application code to complete before attempting to access call history.

### .recordCall(callLog)

Expand All @@ -85,7 +85,7 @@ Returns a Boolean indicating whether `fetch` was called the expected number of t

A single name or an array of names can be passed in the `routeNames` parameter to check only certain routes. If no routeNames are passed it runs over all routes.

### .flush(waitForResponseMethods)
### .flush(waitForBody)

Returns a `Promise` that resolves once all fetches handled by fetch-mock have resolved

Expand Down
File renamed without changes.
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ A boolean indicating whether or not to remove the fallback route (added using `.

Clears all data recorded for `fetch`'s calls.

## unmockGlobal()
## .unmockGlobal()

Restores global `fetch` to its original state if `.mockGlobal()` or `.spyGlobal()` have been used .

Expand Down
File renamed without changes.
Original file line number Diff line number Diff line change
Expand Up @@ -8,26 +8,26 @@ On any `fetch-mock` instance, set configuration options directly on the `fetchMo

```js
const fetchMock = require('fetch-mock');
fetchMock.config.sendAsJson = false;
fetchMock.config.matchPartialBody = false;
```

## Available options

Options marked with a `†` can also be overridden for individual calls to `.mock(matcher, response, options)` by setting as properties on the `options` parameter
Options marked with a `†` can also be overridden for individual calls to `.route(matcher, response, options)` by setting as properties on the `options` parameter

### includeContentLength<sup>†</sup>

`{Boolean}` default: `true`

Sets a `Content-Length` header on each response, with the exception of responses whose body is a `FormData` or `ReadableStream` instance as these are hard/impossible to calculate up front.

### matchPartialBody
### matchPartialBody<sup>†</sup>

`{Boolean}` default: `false`

Match calls that only partially match a specified body json. Uses the [is-subset](https://www.npmjs.com/package/is-subset) library under the hood, which implements behaviour the same as jest's [.objectContaining()](https://jestjs.io/docs/en/expect#expectobjectcontainingobject) method.

### allowRelativeUrls
### allowRelativeUrls<sup>†</sup>

`{Boolean}` default: `false`

Expand Down
32 changes: 32 additions & 0 deletions docs/docs/Usage/installation.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
---
sidebar_position: 1
---

# Installation

Install fetch-mock using

```bash
npm install --save-dev fetch-mock
```

fetch-mock supports both [ES modules](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules) and [commonjs](https://requirejs.org/docs/commonjs.html). The following should work in most environments. Check the [importing the correct version](#usageimporting) section of the docs if you experience problems.

## ES modules

```js
import fetchMock from 'fetch-mock';
```

## Commonjs

```js
const fetchMock = require('fetch-mock');
```

## Using alongside other testing frameworks

When using one of the following frameworks consider using the appropriate wrapper library, which modify/extend fetch-mock to make using it more idiomatic to your testing environment e.g. adding methods equivalent to Jest's `mockRestore()` etc.

- Jest - [@fetch-mock/jest](/fetch-mock/docs/wrappers/jest)
- Vitest - [@fetch-mock/vitest](/fetch-mock/docs/wrappers/vitest)
106 changes: 106 additions & 0 deletions docs/docs/Usage/quickstart.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
---
sidebar_position: 2
---

# Quickstart

## Import fetch-mock

Use one of the following

```js
import fetchMock from 'fetch-mock';
```

```js
const fetchMock = require('fetch-mock');
```

## Mocking fetch

Use the following to replace `fetch` with fetch-mock's implementation of the `fetch` API.

```js
fetchMock.mockGlobal();
```

## Setting up your route

The commonest use case is `fetchMock.route(matcher, response, name)`, where `matcher` is an exact url to match, and `response` is a status code, string or object literal. Optionally you can pass a name for your route as the third parameter. There are many other options for defining your matcher or response, [route documentation](/fetch-mock/docs/API/route/).

You can also use `fetchMock.once()` 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 routes in a single test.

```js
fetchMock
.get('http://good.com/', 200, 'good get')
.post('http://good.com/', 400, 'good post')
.get('http://bad.com/', 500, 'bad get');
```

## Analysing calls to your mock

You can use the names you gave your routes to check if they have been called.

- `fetchMock.called(name)` reports if any calls were handled by your route. If you just want to check `fetch` was called at all then do not pass in a name.
- `fetchMock.lastCall(name)` will return a CallLog object that will give you access to lots of metadata about the call, including the original arguments passed in to `fetch`.
- `fetchMock.done()` will tell you if `fetch` was called the expected number of times.

```js
assert(fetchMock.called('good get'));
assertEqual(fetchMock.lastCall('good get').query['search'], 'needle');
```

## Tearing down your mock

- `fetchMock.clearHistory()` clears all the records of calls made to `fetch`.
- `fetchMock.removeRoutes()` removes all the routes set up.
- `fetchMock.unmockGlobal()` resets `fetch` to its original implementation.

## Example

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

```js
export async function makeRequest() {
const res = await fetch('http://example.com/my-url', {
headers: {
user: 'me',
},
});
return res.json();
}
```

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

```js
import { makeRequest } from './make-request';
import fetchMock from 'fetch-mock';

// Mock the fetch() global to return a response
fetchMock.mockGlobal().get(
'http://httpbin.org/my-url',
{ hello: 'world' },
{
delay: 1000, // fake a slow network
headers: {
user: 'me', // only match requests with certain headers
},
},
);

const data = await makeRequest();
console.log('got data', data);

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

Result:

```bash
$ node mocked.js
'got data' { hello: 'world' }
```
16 changes: 16 additions & 0 deletions docs/docs/Usage/requirements.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
---
sidebar_position: 0.5
---

# Requirements

fetch-mock requires the following to run:

- Either
- [Node.js](https://Node.js.org/) 18+
- A modern browser implementing the `fetch` API.
- [npm](https://www.npmjs.com/package/npm) (normally comes with Node.js)

For usage in older versions of Node.js or older browsers consider [using an older version of fetch-mock](/fetch-mock/docs/legacy-api).

If using node-fetch in your application fetch-mock@12 and above may work for you, but the fetch-mock test suite does not run against node-fetch, so it may be safer to use an [older version of fetch-mock](http://localhost:3000/fetch-mock/docs/legacy-api/) that is tested against node-fetch and is less likely to introduce breaking changes.
39 changes: 39 additions & 0 deletions docs/docs/Usage/upgrade-guide.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
---
title: Upgrade guide
---

fetch-mock@12 has many breaking changes compared to fetch-mock@11:

The [@fetch-mock/codemods](https://www.npmjs.com/package/@fetch-mock/codemods) library provides a tool that will attempt to fix most of these automatically, and its readme contains advice on which manual changes to make alongside these.

## Summary of changes

### `.mock()` method removed

This combined adding a route with mocking the global instance of `fetch`. These are now split into 2 methods: `.route()` and `.mockGlobal()`.

## Reset methods changed

`.reset()`, `.restore()`, `.resetBehavior()` and `.resetHistory()` have been removed and replaced with [methods that are more granular and clearly named](/fetch-mock/docs/API/resetting). Note that the [jest](/fetch-mock/docs/wrappers/jest) and [vitest](/fetch-mock/docs/wrappers/vitest) wrappers for fetch-mock still implement `.mockClear()`, `mockReset()` and `mockRestore()`.

## Call history methods changed

The filtering behaviour has been rewritten around named routes, and methods return CallLog objects that contain far more metadata about the call. [Call history docs](/fetch-mock/docs/API/CallHistory)

## Some convenience routing methods removed

`getOnce()` and `getAnyOnce()`. have all been removed, but the behaviour can still be implemented by the user as follows:

- `getOnce()` -> `get(url, response, {repeat: 1})`
- `getAnyOnce()` -> `get('*', response, {repeat: 1})`

## Options removed

- `overwriteRoutes` - this reflects that multiple routes using the same underlying matcher but different options no longer throw an error.
- `warnOnFallback` - given the improved state of node.js debugging tools compared to when fetch-mock was first written, this debugging utilty has been removed.
- `sendAsJson` - fetch-mock@12 implements streams more robustly than previous options, so the user no longer needs to flag when an object response should be converted to JSON.
- `fallbackToNetwork` - The [`spyGlobal()` method](/fetch-mock/docs/API/mocking-and-spying#spyglobal) should now be used.

## `sandbox()` method removed

This was principally used when mocking node-fetch referenced as a local variable. Given that `fetch` is now available as a native global it's less useful and has been removed. If necessary to mock a local instance of node-fetch use [`.fetchHandler`](/fetch-mock/docs/API/mocking-and-spying#fetchhandler)
41 changes: 41 additions & 0 deletions docs/docs/index.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
---
title: Overview
sidebar_position: 0
---

fetch-mock is the most comprehensive library for mocking the fetch API.

It allows mocking http requests made using [fetch](https://fetch.spec.whatwg.org/) or a library imitating its api, such as [node-fetch](https://www.npmjs.com/package/node-fetch).

It supports most JavaScript environments, including browsers, Node.js, web workers and service workers.

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

## Examples

```js
import fetchMock from 'fetch-mock';
fetchMock.mockGlobal().route('http://example.com', 200);
const res = await fetch('http://example.com');
assert(res.ok);
```

```js
import fetchMock from 'fetch-mock';

fetchMock
.mockGlobal()
.route({
express: '/api/users/:user'
expressParams: {user: 'kenneth'}
}, {
userData: {
email: '[email protected]'
}
}, 'userDataFetch');

const res = await fetch('http://example.com/api/users/kenneth');
assert(fetchMock.called('userDataFetch'))
const data = await res.json();
assertEqual(data.userData.email, '[email protected]')
```
5 changes: 5 additions & 0 deletions docs/docs/legacy-api/API/_category_.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"position": 2,
"collapsible": false,
"collapsed": false
}
5 changes: 5 additions & 0 deletions docs/docs/legacy-api/Usage/_category_.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"position": 1,
"collapsible": false,
"collapsed": false
}
8 changes: 8 additions & 0 deletions docs/docs/legacy-api/index.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
---
sidebar_label: Legacy API
sidebar_position: 800
---

# Legacy API docs

This documentation is for version 11 and below of fetch-mock
4 changes: 4 additions & 0 deletions docs/docs/wrappers/index.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
---
sidebar_label: Wrappers
sidebar_position: 8
---
Loading
Loading