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/abort mid stream #865

Draft
wants to merge 41 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
41 commits
Select commit Hold shift + click to select a range
9253f05
fix: force bodies which are in the middel of being read to be abortable
wheresrhys Oct 22, 2024
3dd239c
Update Router.ts
wheresrhys Oct 23, 2024
0f7e1d2
docs: restructured so that @fetch-mock/core docs are now fetch-mock
wheresrhys Sep 26, 2024
98efcaf
docs: now structured in a pleasing way to differentiate legacy from new
wheresrhys Sep 26, 2024
795c5b5
docs: continued restructuring v12 docs
wheresrhys Oct 13, 2024
5126d4c
docs: duplicated legacy usage folder in new docs
wheresrhys Oct 13, 2024
188e6f5
docs: updates usage docs for v12
wheresrhys Oct 13, 2024
f38dc65
docs: update requirements docs for v12
wheresrhys Oct 13, 2024
b089bf1
docs: update installation docs for v12
wheresrhys Oct 13, 2024
4a25f90
docs: update quickstart for v12
wheresrhys Oct 13, 2024
341167d
docs: update configuration docs for v12
wheresrhys Oct 13, 2024
d6ab47d
docs: removed old docs overview page
wheresrhys Oct 13, 2024
25db854
docs: fix links and structure in v12 docs
wheresrhys Oct 20, 2024
a67e83b
docs: written upgrade guide
wheresrhys Oct 20, 2024
b4e6743
docs: bring vitest docs into website
wheresrhys Oct 20, 2024
262aba5
docs: bring jest docs into website
wheresrhys Oct 20, 2024
ca9fcad
chore: altered core manifests to be called fetch-mock
wheresrhys Oct 20, 2024
b6f3aeb
feat!: Replaced legacy fetch-mock code with fetch-mock/core code
wheresrhys Oct 20, 2024
63b0996
build: fix types
wheresrhys Oct 20, 2024
393396f
test: remove old fetch-mock/core from module compat tests
wheresrhys Oct 20, 2024
e853b3d
chore: lint
wheresrhys Oct 20, 2024
b26dd01
test: use npx when integration testing codemods
wheresrhys Oct 20, 2024
4c0fc0a
chore: pin node to v20
wheresrhys Oct 23, 2024
7ed0a7d
test: set longer timeout on codemod integration tests
wheresrhys Oct 23, 2024
d683ae6
build: fix types:check job in CI
wheresrhys Oct 23, 2024
38b0dd3
docs: fix all broken links
wheresrhys Oct 23, 2024
1907d88
docs: make it clear new docs site si for v12
wheresrhys Oct 24, 2024
109bf58
build: remove core module from release-please config
wheresrhys Oct 24, 2024
20a2624
chore: release main
github-actions[bot] Oct 24, 2024
1f4466a
Fix typo in jest doc
j0k3r Oct 25, 2024
5fe2ce0
docs: document use of URL polyfill with react-native
wheresrhys Oct 25, 2024
6ac6f0c
Update requirements.md
wheresrhys Oct 25, 2024
84e247b
fix: clearHistory() can deal with unmatched calls
wheresrhys Oct 27, 2024
219534d
chore: release main
github-actions[bot] Oct 27, 2024
a914fce
fix: allow sending responses with status 0
wheresrhys Oct 28, 2024
d4f936b
chore: release main
github-actions[bot] Oct 28, 2024
1465078
fix: use file extension to avoid import errors for vitest and jest wr…
wheresrhys Oct 30, 2024
4e16957
test: fix jest tests
wheresrhys Oct 30, 2024
d1f83c6
chore: release main
github-actions[bot] Oct 30, 2024
5746f3b
test: add failing tests for aborting response bodies
wheresrhys Oct 25, 2024
7ee9479
test: tweaks to aborted stream tests
wheresrhys Nov 2, 2024
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
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
7 changes: 3 additions & 4 deletions .release-please-manifest.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
{
"packages/core": "0.7.1",
"packages/fetch-mock": "11.1.5",
"packages/vitest": "0.1.5",
"packages/jest": "0.1.1",
"packages/fetch-mock": "12.0.2",
"packages/vitest": "0.2.3",
"packages/jest": "0.2.3",
"packages/codemods": "0.1.1"
}
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.
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.
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
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' }
```
23 changes: 23 additions & 0 deletions docs/docs/Usage/requirements.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
---
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.

## Usage with react-native

As react-native ships with a non-spec-compliant version of the URL and URLSearchParams classes, fetch-mock will not run in a react-native environment unless you also include [react-native-url-polyfill](https://www.npmjs.com/package/react-native-url-polyfill). You can either:

1. Include it in your application code. This will add approx 11kb of gzipped code to your bundle.
2. Include it in your test files only. If doing this, its recommended that you have some integration tests that _don't_ use fetch-mock in order to avoid inserting behaviour into your application that relies on the polyfill.
Loading