Skip to content

Commit 756ff58

Browse files
author
lsimone
committed
Merge remote-tracking branch 'lsimone/master'
# Conflicts: # README.md # src/index.d.ts # src/index.js
2 parents dea14d3 + c207011 commit 756ff58

13 files changed

+7561
-90
lines changed

.babelrc

+3
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
{
2+
"presets": ["env"]
3+
}

.gitignore

+2
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,4 @@
11
node_modules
22
npm-debug.log
3+
yarn-error.log
4+
coverage

.npmignore

+2
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
tests
2+
yarn.lock

README.md

+25-24
Original file line numberDiff line numberDiff line change
@@ -2,22 +2,22 @@
22

33
Fetch is the new way to do HTTP requests in the browser, and it can be used in other environments such as React Native. Jest Fetch Mock allows you to easily mock your `fetch` calls and return the response you need to fake the HTTP requests. It's easy to setup and you don't need a library like `nock` to get going and it uses Jest's built-in support for mocking under the surface. This means that any of the `jest.fn()` methods are also available. For more information on the jest mock API, check their docs [here](https://facebook.github.io/jest/docs/en/mock-functions.html)
44

5-
It currently supports the mocking of the go-to isomorphic polyfill for fetch, [`isomorphic-fetch`](https://github.com/matthew-andrews/isomorphic-fetch), so it supports Node.js and any browser-like runtime.
5+
It currently supports the mocking with the [`cross-fetch`](https://www.npmjs.com/package/cross-fetch) polyfill, so it supports Node.js and any browser-like runtime.
66

77
## Contents
88

9-
* [Usage](#usage)
10-
* [Installation and Setup](#installation-and-setup)
11-
* [Using with Create-React-App](#using-with-create-react-app)
12-
* [API](#api)
13-
* [Examples](#examples)
14-
* [Simple mock and assert](#simple-mock-and-assert)
15-
* [Mocking all fetches](#mocking-all-fetches)
16-
* [Mocking a failed fetch](#mocking-a-failed-fetch)
17-
* [Mocking multiple fetches with different responses](#mocking-multiple-fetches-with-different-responses)
18-
* [Mocking multiple fetches with `fetch.mockResponses`](#mocking-multiple-fetches-with-fetchmockresponses)
19-
* [Reset mocks between tests with `fetch.resetMocks`](#reset-mocks-between-tests-with-fetchresetmocks)
20-
* [Using `fetch.mock` to inspect the mock state of each fetch call](#using-fetchmock-to-inspect-the-mock-state-of-each-fetch-call)
9+
- [Usage](#usage)
10+
- [Installation and Setup](#installation-and-setup)
11+
- [Using with Create-React-App](#using-with-create-react-app)
12+
- [API](#api)
13+
- [Examples](#examples)
14+
- [Simple mock and assert](#simple-mock-and-assert)
15+
- [Mocking all fetches](#mocking-all-fetches)
16+
- [Mocking a failed fetch](#mocking-a-failed-fetch)
17+
- [Mocking multiple fetches with different responses](#mocking-multiple-fetches-with-different-responses)
18+
- [Mocking multiple fetches with `fetch.mockResponses`](#mocking-multiple-fetches-with-fetchmockresponses)
19+
- [Reset mocks between tests with `fetch.resetMocks`](#reset-mocks-between-tests-with-fetchresetmocks)
20+
- [Using `fetch.mock` to inspect the mock state of each fetch call](#using-fetchmock-to-inspect-the-mock-state-of-each-fetch-call)
2121

2222
## Usage
2323

@@ -51,6 +51,8 @@ Add the setupFile to your jest config in `package.json`:
5151

5252
If you are using [Create-React-App](https://github.com/facebookincubator/create-react-app) (CRA), the code for `setupTest.js` above should be placed into `src/setupTests.js` in the root of your project. CRA automatically uses this filename by convention in the Jest configuration it generates. Similarly, changing to your `package.json` is not required as CRA handles this when generating your Jest configuration.
5353

54+
### For Ejected Create React Apps _ONLY_:
55+
5456
> Note: Keep in mind that if you decide to "eject" before creating src/setupTests.js, the resulting package.json file won't contain any reference to it, so you should manually create the property setupTestFrameworkScriptFile in the configuration for Jest, something like the [following](https://github.com/facebook/create-react-app/blob/master/packages/react-scripts/template/README.md#srcsetuptestsjs-1):
5557
5658
```JSON
@@ -63,13 +65,13 @@ If you are using [Create-React-App](https://github.com/facebookincubator/create-
6365

6466
### Mock Responses
6567

66-
* `fetch.mockResponse(bodyOrFunction, init): fetch` - Mock all fetch calls
67-
* `fetch.mockResponseOnce(bodyOrFunction, init): fetch` - Mock each fetch call independently
68-
* `fetch.once(bodyOrFunction, init): fetch` - Alias for mockResponseOnce
69-
* `fetch.mockResponses(...responses): fetch` - Mock multiple fetch calls independently
70-
* Each argument is an array taking `[bodyOrFunction, init]`
71-
* `fetch.mockReject(errorOrFunction): fetch` - Mock all fetch calls, letting them fail directly
72-
* `fetch.mockRejectOnce(errorOrFunction): fetch` - Let the next fetch call fail directly
68+
- `fetch.mockResponse(bodyOrFunction, init): fetch` - Mock all fetch calls
69+
- `fetch.mockResponseOnce(bodyOrFunction, init): fetch` - Mock each fetch call independently
70+
- `fetch.once(bodyOrFunction, init): fetch` - Alias for mockResponseOnce
71+
- `fetch.mockResponses(...responses): fetch` - Mock multiple fetch calls independently
72+
- Each argument is an array taking `[bodyOrFunction, init]`
73+
- `fetch.mockReject(errorOrFunction): fetch` - Mock all fetch calls, letting them fail directly
74+
- `fetch.mockRejectOnce(errorOrFunction): fetch` - Let the next fetch call fail directly
7375

7476
### Functions
7577

@@ -92,11 +94,10 @@ fetch.mockReject(new Promise((resolve, reject) => {
9294
}))
9395
```
9496

95-
9697
### Mock utilities
9798

98-
* `fetch.resetMocks()` - Clear previously set mocks so they do not bleed into other mocks
99-
* `fetch.mock` - The mock state for your fetch calls. Make assertions on the arguments given to `fetch` when called by the functions you are testing. For more information check the [Jest docs](https://facebook.github.io/jest/docs/en/mock-functions.html#mock-property)
99+
- `fetch.resetMocks()` - Clear previously set mocks so they do not bleed into other mocks
100+
- `fetch.mock` - The mock state for your fetch calls. Make assertions on the arguments given to `fetch` when called by the functions you are testing. For more information check the [Jest docs](https://facebook.github.io/jest/docs/en/mock-functions.html#mock-property)
100101

101102
For information on the arguments body and init can take, you can look at the MDN docs on the Response Constructor function, which `jest-fetch-mock` uses under the surface.
102103

@@ -438,7 +439,7 @@ describe('getYear action creator', () => {
438439
```js
439440
// api.js
440441

441-
import 'isomorphic-fetch'
442+
import 'cross-fetch'
442443

443444
export function APIRequest(who) {
444445
if (who === 'facebook') {

package-lock.json

-59
This file was deleted.

package.json

+16-4
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,11 @@
11
{
22
"name": "jest-fetch-mock",
3-
"version": "1.6.4",
3+
"version": "1.7.5",
44
"description": "fetch mock for jest",
55
"main": "src/index.js",
66
"types": "src/index.d.ts",
77
"scripts": {
8-
"test": "echo \"Error: no test specified\" && exit 1"
8+
"test": "jest"
99
},
1010
"repository": {
1111
"type": "git",
@@ -23,13 +23,25 @@
2323
},
2424
"homepage": "https://github.com/jefflau/jest-fetch-mock#readme",
2525
"dependencies": {
26-
"@types/jest": "^23.0.0",
27-
"isomorphic-fetch": "^2.2.1",
26+
"cross-fetch": "^2.2.2",
2827
"promise-polyfill": "^7.1.1"
2928
},
29+
"devDependencies": {
30+
"babel-core": "^6.26.3",
31+
"babel-jest": "^23.4.2",
32+
"babel-preset-env": "^1.7.0",
33+
"jest": "^23.5.0",
34+
"regenerator-runtime": "^0.12.1"
35+
},
3036
"prettier": {
3137
"semi": false,
3238
"editor.formatOnSave": true,
3339
"singleQuote": true
40+
},
41+
"jest": {
42+
"automock": false,
43+
"setupFiles": [
44+
"./setupJest.js"
45+
]
3446
}
3547
}

setupJest.js

+1
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
global.fetch = require('jest-fetch-mock')

src/index.d.ts

+1
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ declare module "jest-fetch-mock" {
1212
(input?: string | Request, init?: RequestInit): Promise<Response>;
1313
mockResponse(body: string | Function, init?: MockParams): Fetch;
1414
mockResponseOnce(body: string | Function, init?: MockParams): Fetch;
15+
once(body: string, init?: MockParams): Fetch;
1516
mockResponses(...responses : Array<[string] | [string, MockParams]>): Fetch;
1617
mockReject(error?: Error | Function): Fetch;
1718
mockRejectOnce(error?: Error | Function): Fetch;

src/index.js

+11-3
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,8 @@
1-
require('isomorphic-fetch')
1+
const crossFetch = require('cross-fetch')
2+
global.fetch = crossFetch
3+
global.Response = crossFetch.Response
4+
global.Headers = crossFetch.Headers
5+
global.Request = crossFetch.Request
26

37
if (!Promise) {
48
Promise = require('promise-polyfill')
@@ -8,8 +12,12 @@ if (!Promise) {
812

913
const ActualResponse = Response
1014

11-
function ResponseWrapper (body, init) {
12-
if (body && typeof body.constructor === 'function' && body.constructor.__isFallback) {
15+
function ResponseWrapper(body, init) {
16+
if (
17+
body &&
18+
typeof body.constructor === 'function' &&
19+
body.constructor.__isFallback
20+
) {
1321
const response = new ActualResponse(null, init)
1422
response.body = body
1523

tests/api.js

+48
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
import 'cross-fetch/polyfill'
2+
3+
export async function APIRequest(who) {
4+
if (who === 'facebook') {
5+
const call1 = fetch('https://facebook.com/someOtherResource').then(res =>
6+
res.json()
7+
)
8+
const call2 = fetch('https://facebook.com').then(res => res.json())
9+
return Promise.all([call1, call2])
10+
} else if (who === 'twitter') {
11+
return fetch('https://twitter.com').then(res => res.json())
12+
} else {
13+
return fetch('https://google.com').then(res => res.json())
14+
}
15+
}
16+
17+
export function APIRequest2(who) {
18+
if (who === 'google') {
19+
return fetch('https://google.com').then(res => res.json())
20+
} else {
21+
return 'no argument provided'
22+
}
23+
}
24+
25+
export function request() {
26+
return fetch('https://randomuser.me/api', {})
27+
.then(response => {
28+
const contentType = response.headers.get('content-type')
29+
30+
if (/application\/json/.test(contentType)) {
31+
return response.json()
32+
}
33+
34+
if (/text\/csv/.test(contentType)) {
35+
return response.blob()
36+
}
37+
38+
if (!contentType || /^text\/|charset=utf-8$/.test(contentType)) {
39+
return response.text()
40+
}
41+
42+
return response
43+
})
44+
.catch(error => {
45+
const errorData = JSON.parse(error)
46+
throw new Error(errorData.error)
47+
})
48+
}

0 commit comments

Comments
 (0)