Skip to content

Commit

Permalink
Merge pull request #846 from wheresrhys/rhys/fm-12-docs
Browse files Browse the repository at this point in the history
Rhys/fm 12 docs
  • Loading branch information
wheresrhys authored Oct 24, 2024
2 parents d9a60ef + a2b58d0 commit c497cd0
Show file tree
Hide file tree
Showing 160 changed files with 706 additions and 7,140 deletions.
1 change: 0 additions & 1 deletion .circleci/config.yml
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,6 @@ jobs:
steps:
- *workspace
- run: npm run types:check --noEmit=true
- run: npm run types:check -w packages/fetch-mock
test:
<<: *nodelts
steps:
Expand Down
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 @@ -49,19 +49,19 @@ Retrieve all calls to `fetch` matched by a particular named route.
#### matcher

`{String|RegExp|function|Object}`
Any matcher compatible with the [route api](#api-mockingmock_matcher) can be passed in to filter the calls arbitrarily.
Any matcher compatible with the [route api](/fetch-mock/docs/API/route/matcher) can be passed in to filter the calls arbitrarily.

### options

`{Object}`

An options object compatible with the [route api](#api-mockingmock_options) to be used to filter the list of calls further.
An options object compatible with the [route api](/fetch-mock/docs/API/route/options) to be used to filter the list of calls further.

## Methods

`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.
File renamed without changes.
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,9 @@ These methods allow defining routes for common use cases while avoiding writing

Specifies how to respond to calls to `fetch` that don't match any routes.

It accepts any [response](#api-mockingmock_response) compatible with `.route()`. If no argument is passed, then every unmatched call will receive a `200` response.
It accepts any [response](/fetch-mock/docs/API/route/response) compatible with `.route()`. If no argument is passed, then every unmatched call will receive a `200` response.

See also [.spy()](/fetch-mock/docs/@fetch-mock/core/mocking-and-spying#spymatcher-name)
See also [.spy()](/fetch-mock/docs/API/mocking-and-spying#spymatcher-name)

## .sticky()

Expand Down
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.
File renamed without changes.
Original file line number Diff line number Diff line change
Expand Up @@ -89,8 +89,8 @@ When the `express:` keyword is used in a string matcher, it can be combined with

The values of express parameters are made available in the `expressParams` property when

- [Inspecting call history](/fetch-mock/docs/@fetch-mock/core/CallHistory#calllog-schema)
- [Using a function to construct a response](/fetch-mock/docs/@fetch-mock/core/route/response#function)
- [Inspecting call history](/fetch-mock/docs/API/CallHistory#calllog-schema)
- [Using a function to construct a response](/fetch-mock/docs/API/route/response#function)

### Multiple url matchers

Expand Down Expand Up @@ -149,7 +149,7 @@ Match only requests that have these query parameters set (in any order). Query p

Match only requests that send a JSON body with the exact structure and properties as the one provided here.

Note that if matching on body _and_ using `Request` instances in your source code, this forces fetch-mock into an asynchronous flow _before_ it is able to route requests effectively. This means no [inspection methods](#api-inspectionfundamentals) can be used synchronously. You must first either await the fetches to resolve, or `await fetchMock.callHistory.flush()`. The popular library [Ky](https://github.com/sindresorhus/ky) uses `Request` instances internally, and so also triggers this mode.
Note that if matching on body _and_ using `Request` instances in your source code, this forces fetch-mock into an asynchronous flow _before_ it is able to route requests effectively. This means no [call history methods](/fetch-mock/docs/API/CallHistory) can be used synchronously. You must first either await the fetches to resolve, or `await fetchMock.callHistory.flush()`. The popular library [Ky](https://github.com/sindresorhus/ky) uses `Request` instances internally, and so also triggers this mode.

e.g.`{body: { "key1": "value1", "key2": "value2" }}`

Expand All @@ -166,7 +166,7 @@ When matching a body, this option ignores any properties not mentioned in the ma
}
```

This option can also be [set in the global configuration](/fetch-mock/docs/@fetch-mock/core/configuration)
This option can also be [set in the global configuration](/fetch-mock/docs/Usage/configuration)

## Function matchers

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ A unique string naming the route. Used to subsequently retrieve references to th

### response

When using pattern 3. above, `response` can be passed as a property on the options object. See the [response documentation](#usageapimock_response) for valid values.
When using pattern 3. above, `response` can be passed as a property on the options object. See the [response documentation](/fetch-mock/docs/API/route/response) for valid values.

### repeat

Expand All @@ -40,10 +40,10 @@ Avoids a route being removed when `removeRoutes()` is called.

`{Boolean}`

See [global configuration](#usageconfiguration)
See [global configuration](/fetch-mock/docs/Usage/configuration)

### includeContentLength

`{Boolean}`

See [global configuration](#usageconfiguration)
See [global configuration](/fetch-mock/docs/Usage/configuration)
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ A `Promise` that resolves to any of the options documented above e.g. `new Promi

`{Function}`

A function that is passed a [`CallLog`](/fetch-mock/docs/@fetch-mock/core/CallHistory#calllog-schema) and returns any of the options documented above (including `Promise`).
A function that is passed a [`CallLog`](/fetch-mock/docs/API/CallHistory#calllog-schema) and returns any of the options documented above (including `Promise`).

### Examples

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.

## 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)
Loading

0 comments on commit c497cd0

Please sign in to comment.