jest-fetch-mock vs fetch-mock-jest
在 Jest 测试中模拟 fetch 请求的两种主流方案
jest-fetch-mockfetch-mock-jest

在 Jest 测试中模拟 fetch 请求的两种主流方案

fetch-mock-jest 和 jest-fetch-mock 都是用于在 Jest 测试环境中模拟全局 fetch API 的工具库,旨在简化对网络请求的拦截、断言和响应控制。它们都允许开发者在不发起真实 HTTP 请求的情况下,验证组件或函数是否正确调用了 fetch,并能自定义返回结果以覆盖各种测试场景(如成功、失败、加载状态等)。尽管目标一致,但两者在实现方式、API 设计和与 Jest 的集成深度上存在显著差异。

npm下载趋势

3 年

GitHub Stars 排名

统计详情

npm包名称
下载量
Stars
大小
Issues
发布时间
License
jest-fetch-mock1,485,89889475.9 kB73 个月前MIT
fetch-mock-jest496,52360-176 年前MIT

在 Jest 中模拟 fetch:fetch-mock-jest vs jest-fetch-mock 深度对比

在现代前端测试中,模拟 fetch 是验证数据流、错误处理和加载状态的关键环节。fetch-mock-jest 和 jest-fetch-mock 是两个广泛使用的解决方案,但它们的设计哲学和使用体验截然不同。本文从工程实践角度,对比二者的核心机制、API 差异和适用场景。

🔧 核心机制:底层如何工作?

jest-fetch-mock 直接将全局 fetch 替换为一个 Jest spy 函数,并内置了响应控制逻辑。这意味着你可以像使用普通 Jest mock 一样调用 .mockResolvedValue()、.mockImplementation(),也能直接使用 .toHaveBeenCalledTimes() 等断言。

// jest-fetch-mock 示例
import 'jest-fetch-mock';
fetchMock.enableMocks(); // 将全局 fetch 替换为 mock

beforeEach(() => {
  fetch.resetMocks(); // 自动清除调用记录
});

test('调用 fetch 获取用户', async () => {
  fetch.mockResolvedValue({ json: () => Promise.resolve({ id: 1 }) });
  await getUser();
  expect(fetch).toHaveBeenCalledWith('/api/user');
  expect(fetch).toHaveBeenCalledTimes(1);
});

fetch-mock-jest 本身并不实现 mock 逻辑,而是作为 fetch-mock 库的 Jest 适配器。它确保 fetch-mock 在 Jest 环境中正常工作(例如兼容模块系统),但所有 mock 规则和断言都通过 fetch-mock 的 API 完成。

// fetch-mock-jest 示例
import fetchMock from 'fetch-mock-jest';

beforeEach(() => {
  fetchMock.reset(); // 清除 mock 规则和调用记录
});

test('调用 fetch 获取用户', async () => {
  fetchMock.get('/api/user', { id: 1 });
  const user = await getUser();
  expect(user).toEqual({ id: 1 });
  expect(fetchMock.called('/api/user')).toBe(true);
});

⚠️ 注意:截至 2024 年,fetch-mock-jest 的 npm 页面明确标注其为 fetch-mock 的 Jest 兼容包装,而 jest-fetch-mock 是独立维护的专用库。

🧪 断言方式:如何验证行为?

jest-fetch-mock 利用 Jest 原生的 mock 函数特性,支持标准的 .toHaveBeenCalledWith()、.toHaveBeenCalledTimes() 等断言,对熟悉 Jest 的开发者非常友好。

// jest-fetch-mock 的断言
expect(fetch).toHaveBeenCalledWith('/api/data', {
  method: 'POST',
  body: JSON.stringify({ name: 'test' })
});
expect(fetch).toHaveReturnedTimes(1);

fetch-mock-jest 使用 fetch-mock 自有的断言方法,如 .called(), .calls(), .lastCall() 等,语义清晰但需学习新 API。

// fetch-mock-jest 的断言
expect(fetchMock.called('/api/data')).toBeTruthy();
const calls = fetchMock.calls('/api/data');
expect(calls[0][1]).toEqual({ method: 'POST', body: JSON.stringify({ name: 'test' }) });

🛠️ Mock 配置:如何定义响应?

jest-fetch-mock 依赖 Jest 的 mock 函数机制,通常通过 .mockResolvedValue() 或 .mockImplementation() 设置响应。

// jest-fetch-mock:设置响应
fetch.mockResolvedValueOnce({
  json: () => Promise.resolve({ success: true })
});

// 或模拟错误
fetch.mockRejectedValueOnce(new Error('Network error'));

fetch-mock-jest 提供声明式 API,支持按 URL、方法、请求头等条件匹配,并可直接返回对象、Promise 或函数。

// fetch-mock-jest:设置响应
fetchMock.post('/api/data', { success: true });
fetchMock.get('/api/fail', 500); // 返回 500 状态码
fetchMock.put('*', { delay: 100, body: { delayed: true } }); // 通配符 + 延迟

🔄 状态管理:如何清理和重置?

jest-fetch-mock 推荐在 beforeEach 中调用 fetch.resetMocks(),这会清除所有 mock 实现和调用记录,符合 Jest 的测试隔离惯例。

beforeEach(() => {
  fetch.resetMocks();
});

fetch-mock-jest 需要调用 fetchMock.reset() 来清除规则和调用历史,也可使用 fetchMock.restore() 完全恢复原生 fetch(通常在 afterAll 中使用)。

beforeEach(() => {
  fetchMock.reset();
});

afterAll(() => {
  fetchMock.restore();
});

🌐 复杂场景支持:通配符、延迟、动态响应

fetch-mock-jest 基于 fetch-mock,天然支持高级功能:

  • 通配符和正则匹配:fetchMock.get('https://api.*.com/*', ...)
  • 请求体检查:fetchMock.post('/api', (url, opts) => opts.body.includes('valid'))
  • 延迟和错误注入:{ delay: 200, throws: new Error('timeout') }
fetchMock.post(
  '/api/upload',
  (url, opts) => {
    if (opts.headers['Content-Type'] !== 'application/json') {
      return { status: 400, body: { error: 'Invalid type' } };
    }
    return { status: 201, body: { id: '123' } };
  }
);

jest-fetch-mock 本身不提供这些高级匹配能力,但可通过 .mockImplementation() 手动实现类似逻辑,代码会更冗长。

fetch.mockImplementation((url, opts) => {
  if (url === '/api/upload' && opts.headers['Content-Type'] !== 'application/json') {
    return Promise.resolve({
      status: 400,
      json: () => Promise.resolve({ error: 'Invalid type' })
    });
  }
  return Promise.resolve({
    status: 201,
    json: () => Promise.resolve({ id: '123' })
  });
});

📦 Setup 配置:如何集成到项目?

jest-fetch-mock 通常通过 Jest 的 setupFilesAfterEnv 全局启用:

// jest.config.js
module.exports = {
  setupFilesAfterEnv: ['<rootDir>/src/setupTests.js']
};

// src/setupTests.js
import 'jest-fetch-mock';
fetchMock.enableMocks();

fetch-mock-jest 无需特殊 setup,直接在测试文件中导入即可使用,但需确保在测试前调用 fetchMock.reset()。

✅ 总结:如何选择?

维度jest-fetch-mockfetch-mock-jest
核心机制替换 fetch 为 Jest spy作为 fetch-mock 的 Jest 适配器
断言方式Jest 原生断言(.toHaveBeenCalledWith)fetch-mock 专属断言(.called())
响应配置通过 .mockResolvedValue() 等声明式 API(.get(), .post())
高级匹配需手动实现内置支持(正则、请求体检查等)
状态重置fetch.resetMocks()fetchMock.reset()
学习成本低(Jest 开发者熟悉)中(需了解 fetch-mock)
  • 选 jest-fetch-mock:如果你的团队重度依赖 Jest 的 mock 生态,希望用最少的配置快速开始,且测试场景相对简单(如固定 URL、基本成功/失败)。
  • 选 fetch-mock-jest:如果你需要复杂的匹配规则(如通配符、动态响应)、精细的请求验证,或已在项目中使用 fetch-mock,愿意接受稍高的学习成本以换取更强的表达能力。

无论选择哪个,都要确保在 beforeEach 中正确重置状态,避免测试间污染 —— 这是保证测试可靠性的关键。

如何选择: jest-fetch-mock vs fetch-mock-jest

  • jest-fetch-mock:

    选择 jest-fetch-mock 如果你追求与 Jest 更紧密的集成体验,例如自动重置 mock 状态、开箱即用的 .toHaveBeenCalledTimes() 等 Jest 原生断言支持,以及更简单的全局 setup 方式。它内部直接操作全局 fetch 并将其替换为 Jest spy,因此更适合希望快速上手、减少配置、依赖 Jest 生态惯用法的团队。

  • fetch-mock-jest:

    选择 fetch-mock-jest 如果你希望使用一个轻量级、声明式 API 的封装,并且项目已经依赖 fetch-mock 或倾向于其灵活的匹配规则(如基于 URL 模式、方法、请求体等)。它适合需要精细控制 mock 行为、支持复杂路由匹配的场景,但需手动管理 mock 状态(如清除、重置)。注意:该包仅为 fetch-mock 提供 Jest 兼容层,核心能力来自 fetch-mock 本身。

jest-fetch-mock的README

Jest Fetch Mock

npm version npm downloads Node.js CI

Fetch is the canonical way to do HTTP requests in the browser, and it can be used in other environments such as Node.js and 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 set up 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 the docs here.

It builds on the environment's own fetch primitives wherever they exist (Node 18+, Jest 28+ — your mocked responses are real native Response objects), and falls back to the bundled cross-fetch classes only in environments without fetch, such as jest-environment-jsdom.

Using Vitest? Use the actively maintained fork vitest-fetch-mock instead.

Need to mock a whole API surface (handlers per route, shared between tests and dev)? Consider MSW. Jest Fetch Mock is deliberately smaller: a drop-in jest.fn() for fetch.

Contents

Usage

Package Installation

To setup your fetch mock you need to do the following things:

$ npm install --save-dev jest-fetch-mock

The simplest setup is the bundled one-liner in setupFilesAfterEnv:

"jest": {
  "automock": false,
  "setupFilesAfterEnv": [
    "jest-fetch-mock/setup"
  ]
}

Or with your own setup file (if you have one already, add the enableMocks() line to it):

//setupJest.js or similar file
require('jest-fetch-mock').enableMocks()
"jest": {
  "automock": false,
  "setupFilesAfterEnv": [
    "./setupJest.js"
  ]
}

With this done, you'll have fetch and fetchMock available on the global scope. Fetch will be used as usual by your code and you'll use fetchMock in your tests.

setupFiles also works, with one caveat worth knowing:

⚠️ The resetMocks gotcha — read this if fetch() mysteriously returns undefined.

If your Jest config sets resetMocks: true (Create React App does this by default since CRA 4.0.1), Jest wipes the mock's implementation before every test — after your setup ran, historically leaving fetch as an empty jest.fn() resolving undefined. This was the single most-reported issue with this library (#81, #78, #104, #202).

Since 4.0 the mock re-arms itself automatically — as long as enableMocks() runs from setupFilesAfterEnv (as shown above) or a test file. If you must use setupFiles (which runs before the test framework, where the re-arm hook can't be registered), either set "resetMocks": false or re-enable per test:

beforeEach(() => {
  fetchMock.enableMocks()
})

Default not mocked

If you would like to have the fetchMock available in all tests but not enabled, add fetchMock.dontMock() after the ...enableMocks() line in setupJest.js:

// adds the 'fetchMock' global variable and rewires 'fetch' global to call 'fetchMock' instead of the real implementation
require('jest-fetch-mock').enableMocks()
// changes default behavior of fetchMock to use the real 'fetch' implementation and not mock responses
fetchMock.dontMock()

If you want a single test file to return to the default behavior of mocking all responses, add the following to the test file:

beforeEach(() => {
  // if you have an existing `beforeEach` just add the following line to it
  fetchMock.doMock()
})

To enable mocking for specific URLs only:

beforeEach(() => {
  // if you have an existing `beforeEach` just add the following lines to it
  fetchMock.mockIf(/^https?:\/\/example.com.*$/, async (req) => {
    if (req.url.endsWith('/path1')) {
      return 'some response body'
    } else if (req.url.endsWith('/path2')) {
      return {
        body: 'another response body',
        headers: {
          'X-Some-Response-Header': 'Some header value'
        }
      }
    } else {
      return {
        status: 404,
        body: 'Not Found'
      }
    }
  })
})

If you have changed the default behavior to use the real implementation, you can guarantee the next call to fetch will be mocked by using the mockOnce function:

fetchMock.mockOnce('the next call to fetch will always return this as the body')

This function behaves exactly like fetchMock.once but guarantees the next call to fetch will be mocked even if the default behavior of fetchMock is to use the real implementation. You can safely convert all your fetchMock.once calls to fetchMock.mockOnce without a risk of changing their behavior.

To setup for an individual test

For JavaScript add the following line to the start of your test case (before any other requires):

require('jest-fetch-mock').enableMocks()

For TypeScript/ES6 add the following lines to the start of your test case (before any other imports):

import { enableFetchMocks } from 'jest-fetch-mock'
enableFetchMocks()

Using with TypeScript

The package ships its own type definitions — no @types/jest-fetch-mock needed, and since 4.0 no dependency on @types/jest either (the mock surface is declared structurally, so @jest/globals-only projects type-check cleanly). The definitions need ambient fetch types from either lib: ["dom"] or @types/node ≥ 18 — every Jest project has one of these.

If you receive errors about the fetchMock global not existing, add a global.d.ts file to the root of your project (or add the following line to an existing global file):

import 'jest-fetch-mock'

If you prefer you can also just import the fetchMock in a test case:

import fetchMock from 'jest-fetch-mock'

Typed usage of the most common calls looks like this:

import fetchMock, { MockResponseInit } from 'jest-fetch-mock'

fetchMock.mockResponseOnce(JSON.stringify({ data: '12345' }))

fetchMock.mockResponse(async (req: Request): Promise<MockResponseInit> => ({
  body: 'ok',
  status: 201,
}))

Using with Create-React-App

Create React App is no longer maintained, but plenty of apps built with it still are — so this section stays.

If you are using Create-React-App (CRA), the code for setupJest.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 your package.json is not required as CRA handles this when generating your Jest configuration.

Note that CRA ≥ 4.0.1 generates a Jest config with resetMocks: true — see the resetMocks gotcha above for why that matters and how to handle it.

A note on Node's built-in fetch

Since 4.0, this library builds on the environment's own fetch primitives whenever they exist — under jest-environment-node (Jest 28+, Node 18+) your mocked Responses are real native (undici) responses, instanceof checks work, and nothing your tests didn't ask for is touched. Where the environment provides no fetch (jest-environment-jsdom), the bundled cross-fetch fallback fills exactly the missing globals, as it always did. fetchMock.usingNativeFetch tells you which mode you're in.

Migrating from 3.x

4.0 keeps every 3.x API. Things to check when upgrading:

  • Floors: Node ≥ 18 and Jest ≥ 28 (stay on 3.2.0 for older stacks).
  • In node environments, mocked responses are now native Response objects. If a test asserted node-fetch-specific details, it may need a touch-up (e.g. MIME types serialize as text/csv;charset=utf-8, without the space).
  • disableMocks() now restores the environment's original fetch rather than cross-fetch's.
  • Relative URLs (fetch('/api')) in node environments resolve against http://localhost/ for match predicates; in jsdom the fallback behaves as before.
  • TypeScript: the types no longer force the dom lib onto your compilation and no longer require @types/jest — but they do need ambient fetch types from either lib: ["dom"] or @types/node ≥ 18. Note that under node types (no dom lib), response.json() is Promise<unknown> per undici-types — annotate or cast the result. Previously the forced dom lib masked this as Promise<any>.
  • If you use resetMocks: true in your Jest config, move enableMocks() to setupFilesAfterEnv and the old "fetch returns undefined" footgun disappears entirely.

injectGlobals: false / @jest/globals

The main entry needs the global jest object at import time. If you run with injectGlobals: false, build your instance explicitly:

import { jest } from '@jest/globals'
import createFetchMock from 'jest-fetch-mock/factory'

const fetchMock = createFetchMock(jest)
fetchMock.enableMocks()

One-liner setup

"jest": {
  "setupFilesAfterEnv": ["jest-fetch-mock/setup"]
}

API

Mock Responses

  • fetch.mockResponse(bodyOrFunction, init): fetch - Mock all fetch calls
  • fetch.mockResponseOnce(bodyOrFunction, init): fetch - Mock each fetch call independently
  • fetch.once(bodyOrFunction, init): fetch - Alias for mockResponseOnce(bodyOrFunction, init)
  • fetch.mockResponses(...responses): fetch - Mock multiple fetch calls independently
    • Each argument is an array taking [bodyOrFunction, init], a body string, or a Response
  • fetch.mockReject(errorOrFunction): fetch - Mock all fetch calls, letting them fail directly
  • fetch.mockRejectOnce(errorOrFunction): fetch - Let the next fetch call fail directly
  • fetch.mockAbort(): fetch - Causes all fetch calls to reject with an AbortError DOMException ("The operation was aborted.")
  • fetch.mockAbortOnce(): fetch - Causes the next fetch call to reject with an AbortError DOMException

The body argument can be:

  • a string — used as the response body. To respond with JSON, stringify it yourself: fetch.mockResponse(JSON.stringify({ foo: 'bar' })) (passing a plain object is a common mistake and produces "[object Object]"),
  • a Response object — returned as-is, which is the way to mock binary bodies: fetch.mockResponseOnce(new Response(Buffer.from(myBytes))). Note a Response body can only be read once, so prefer mockResponseOnce (or a function returning a fresh Response) over mockResponse when fetch is called repeatedly,
  • a function — see below.

Functions

Instead of passing body, it is also possible to pass a function that returns a promise (or a plain value). The promise should resolve with a string, an object containing body and init props, or a Response object

i.e:

fetch.mockResponse(() => callMyApi().then(res => ({ body: 'ok' })))
// OR
fetch.mockResponse(() => callMyApi().then(res => 'ok'))
// OR
fetch.mockResponse(() => callMyApi().then(res => new Response('ok')))
// OR synchronously:
fetch.mockResponse(() => 'ok')

The function may take an optional "request" parameter of type Request:

fetch.mockResponse(req =>
  req.url === 'http://myapi/'
    ? callMyApi().then(res => 'ok')
    : Promise.reject(new Error('bad url'))
)

Note: the request "url" is parsed and then printed using the equivalent of new URL(input).href so it may not match exactly with the URLs passed to fetch if they are not fully qualified. For example, passing "http://foo.com" to fetch will result in the request URL being "http://foo.com/" (note the trailing slash).

The same goes for rejects:

fetch.mockReject(() =>
  doMyAsyncJob().then(res => Promise.reject(res.errorToRaise))
)
// OR
fetch.mockReject(req =>
  req.headers.get('content-type') === 'text/plain'
    ? Promise.reject('invalid content type')
    : doMyAsyncJob().then(res => Promise.reject(res.errorToRaise))
)

Mock utilities

  • fetch.resetMocks() - Clear previously set mocks so they do not bleed into other mocks
  • fetch.enableMocks() - Enable fetch mocking by overriding global.fetch and mocking node-fetch
  • fetch.disableMocks() - Disable fetch mocking and restore the environment's original fetch
  • 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
  • fetch.route(urlOrPredicate, bodyOrFunction?, init?) / fetch.routeOnce(...) / fetch.clearRoutes() - Route-based mocking, see Routes
  • fetch.realFetch - The implementation unmatched (dont-mocked) requests pass through to; reassign it in a test to stub the "real" side
  • fetch.defaultResponseInit - Optional init merged under every mocked response's own init — e.g. fetchMock.defaultResponseInit = { headers: { 'Content-Type': 'application/json' } } to default every mock to JSON
  • fetch.usingNativeFetch - true when the environment's own fetch primitives are in use, false when the jsdom fallback engaged
  • createFetchMock(jest) - Build an isolated instance from an explicitly-passed jest object (also importable dependency-free from jest-fetch-mock/factory)

Routes

Since 4.2 you can register several matcher→response pairs that coexist — no more choosing between one big switch function and mockIf calls that replace each other:

fetchMock
  .route('https://api.example.com/session', JSON.stringify({ user: 'jeff' }))
  .route(/\/teams$/, JSON.stringify([{ id: 42 }]))
  .route((req) => req.method === 'POST', async (req) => ({
    status: 201,
    body: await req.text(),
  }))
  • Matchers are the same shapes as mockIf: exact URL string, RegExp, or a (request) => boolean predicate. First registered match wins.
  • The response side accepts everything mockResponse does: a string, a Response, or a sync/async function receiving the Request. Omit it for the default empty 200.
  • routeOnce(...) registers a route that is consumed by its first match.
  • clearRoutes() removes all routes; resetMocks() clears them too.

Precedence: an explicitly queued once-response (mockResponseOnce/once) outranks routes for that call; a matching route outranks the ambient mockResponse body and the conditional gate — so routes still fire when the default is dontMock(), which makes them the clean way to mock only known endpoints and let everything else hit the network:

fetchMock.dontMock() // everything real...
fetchMock.route('https://api.example.com/flags', '{"beta":true}') // ...except this

mockReject()/mockAbort() replace the whole implementation and override routes. Routes compose across setup: register base routes in a beforeEach and add per-test ones inside the test.

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:

https://developer.mozilla.org/en-US/docs/Web/API/Response/Response

Each mocked response or error will return a Mock Function. You can use methods like .toHaveBeenCalledWith to ensure that the mock function was called with specific arguments. For more methods detail, take a look at this.

Examples

In most of the complicated examples below, I am testing my action creators in Redux, but it doesn't have to be used with Redux.

Simple mock and assert

In this simple example I won't be using any libraries. It is a simple fetch request, in this case to google.com. First we setup the beforeEach callback to reset our mocks. This isn't strictly necessary in this example, but since we will probably be mocking fetch more than once, we need to reset it across our tests to assert on the arguments given to fetch. Make sure the function wrapping your test is marked as async.

Once we've done that we can start to mock our response. We want to give it an object with a data property and a string value of 12345 and wrap it in JSON.stringify to JSONify it. Here we use mockResponseOnce, but we could also use once, which is an alias for a call to mockResponseOnce.

We then call the function that we want to test with the arguments we want to test with. We use await to wait until the response resolves, and then assert we have got the correct data back.

Finally we can assert on the .mock state that Jest provides for us to test what arguments were given to fetch and how many times it was called

//api.js
export function APIRequest(who) {
  if (who === 'google') {
    return fetch('https://google.com').then(res => res.json())
  } else {
    return 'no argument provided'
  }
}
//api.test.js
import { APIRequest } from './api'

describe('testing api', () => {
  beforeEach(() => {
    fetch.resetMocks()
  })

  it('calls google and returns data to me', async () => {
    fetch.mockResponseOnce(JSON.stringify({ data: '12345' }))

    //assert on the response
    const res = await APIRequest('google')
    expect(res.data).toEqual('12345')

    //assert on the times called and arguments given to fetch
    expect(fetch.mock.calls.length).toEqual(1)
    expect(fetch.mock.calls[0][0]).toEqual('https://google.com')
  })
})

Mocking all fetches

In this example I am mocking just one fetch call. Any additional fetch calls in the same function will also have the same mock response. For more complicated functions with multiple fetch calls, you can check out the multiple fetches example.

import configureMockStore from 'redux-mock-store' // mock store
import thunk from 'redux-thunk'

const middlewares = [thunk]
const mockStore = configureMockStore(middlewares)

import { getAccessToken } from './accessToken'

describe('Access token action creators', () => {
  it('dispatches the correct actions on successful fetch request', () => {
    fetch.mockResponse(JSON.stringify({ access_token: '12345' }))

    const expectedActions = [
      { type: 'SET_ACCESS_TOKEN', token: { access_token: '12345' } }
    ]
    const store = mockStore({ config: { token: '' } })

    return (
      store
        .dispatch(getAccessToken())
        //getAccessToken contains the fetch call
        .then(() => {
          // return of async actions
          expect(store.getActions()).toEqual(expectedActions)
        })
    )
  })
})

Mocking a failed fetch

In this example I am mocking just one fetch call but this time using the mockReject function to simulate a failed request. Any additional fetch calls in the same function will also have the same mock response.

describe('testing a failed request', () => {
  it('rejects and surfaces the error', async () => {
    fetch.mockReject(new Error('fake error message'))

    await expect(fetch('https://anything.test')).rejects.toThrow(
      'fake error message'
    )
  })
})

Mocking aborted fetches

Fetches can be mocked to act as if they were aborted during the request. This can be done in 4 ways:

  1. Using fetch.mockAbort()
  2. Using fetch.mockAbortOnce()
  3. Passing a request (or request init) with an already-aborted 'signal' to fetch
  4. Passing a request (or request init) with a 'signal' to fetch and an async function to fetch.mockResponse or fetch.mockResponseOnce that causes the signal to abort before returning the response

In every case the fetch promise rejects with an AbortError DOMException whose message is "The operation was aborted." (Before 3.2.0, case 3 threw synchronously instead of rejecting; it now rejects, matching the fetch spec.) Since 4.0, a signal aborted with a custom reason rejects with that reason as-is, and an AbortSignal.timeout() signal rejects with its TimeoutError.

describe('Mocking aborts', () => {
  beforeEach(() => {
    fetch.resetMocks()
    fetch.doMock()
    jest.useFakeTimers()
  })
  afterEach(() => {
    jest.useRealTimers()
  })

  it('rejects with an AbortError', () => {
    fetch.mockAbort()
    return expect(fetch('/')).rejects.toThrow('The operation was aborted')
  })

  it('rejects with an AbortError once then mocks with empty response', async () => {
    fetch.mockAbortOnce()
    await expect(fetch('/')).rejects.toThrow('The operation was aborted')
    await expect(fetch('/').then((res) => res.text())).resolves.toEqual('')
  })

  it('rejects when passed an already aborted abort signal', () => {
    const c = new AbortController()
    c.abort()
    return expect(fetch('/', { signal: c.signal })).rejects.toThrow(
      'The operation was aborted'
    )
  })

  it('rejects when aborted before resolved', async () => {
    const c = new AbortController()
    fetch.mockResponse(async () => {
      jest.advanceTimersByTime(60)
      return ''
    })
    setTimeout(() => c.abort(), 50)
    await expect(fetch('/', { signal: c.signal })).rejects.toThrow(
      'The operation was aborted'
    )
  })
})

Mocking a redirected response

Set the counter option >= 1 in the response init object to mock a redirected response. (Since 4.0 this works in every environment — the flag is applied to the mocked response directly. You can also set url in the init to control response.url.)

fetchMock.mockResponse("<main></main>", {
  counter: 1,
  status: 200,
  statusText: "ok",
});

Mocking multiple fetches with different responses

In this next example, the store does not yet have a token, so we make a request to get an access token first. This means that we need to mock two different responses, one for each of the fetches. Here we can use fetch.mockResponseOnce or fetch.once to mock the response only once and call it twice. Because we return the mocked function, we can chain this jQuery style. It internally uses Jest's mockImplementationOnce. You can read more about it on the Jest documentation

import configureMockStore from 'redux-mock-store'
import thunk from 'redux-thunk'

const middlewares = [thunk]
const mockStore = configureMockStore(middlewares)

import { getAnimeDetails } from './animeDetails'

describe('Anime details action creators', () => {
  it('dispatches requests for an access token before requesting for animeDetails', () => {
    fetch
      .once(JSON.stringify({ access_token: '12345' }))
      .once(JSON.stringify({ name: 'naruto' }))

    const expectedActions = [
      { type: 'SET_ACCESS_TOKEN', token: { access_token: '12345' } },
      { type: 'SET_ANIME_DETAILS', animeDetails: { name: 'naruto' } }
    ]
    const store = mockStore({ config: { token: null } })

    return (
      store
        .dispatch(getAnimeDetails('21049'))
        //getAnimeDetails contains the 2 fetch calls
        .then(() => {
          // return of async actions
          expect(store.getActions()).toEqual(expectedActions)
        })
    )
  })
})

Mocking multiple fetches with fetch.mockResponses

fetch.mockResponses takes as many arguments as you give it, all of which are arrays representing each Response Object. It will then call the mockImplementationOnce for each response object you give it. This reduces the amount of boilerplate code you need to write. An alternative is to use .once and chain it multiple times if you don't like wrapping each response arguments in a tuple/array.

In this example our actionCreator calls fetch 4 times, once for each season of the year and then concatenates the results into one final array. You'd have to write fetch.mockResponseOnce 4 times to achieve the same thing:

describe('getYear action creator', () => {
  it('dispatches the correct actions on successful getSeason fetch request', () => {
    fetch.mockResponses(
      [
        JSON.stringify([{ name: 'naruto', average_score: 79 }]),
        { status: 200 }
      ],
      [
        JSON.stringify([{ name: 'bleach', average_score: 68 }]),
        { status: 200 }
      ],
      [
        JSON.stringify([{ name: 'one piece', average_score: 80 }]),
        { status: 200 }
      ],
      [
        JSON.stringify([{ name: 'shingeki', average_score: 91 }]),
        { status: 200 }
      ]
    )

    const expectedActions = [
      {
        type: 'FETCH_ANIMELIST_REQUEST'
      },
      {
        type: 'SET_YEAR',
        payload: {
          animes: [
            { name: 'naruto', average_score: 7.9 },
            { name: 'bleach', average_score: 6.8 },
            { name: 'one piece', average_score: 8 },
            { name: 'shingeki', average_score: 9.1 }
          ],
          year: 2016
        }
      },
      {
        type: 'FETCH_ANIMELIST_COMPLETE'
      }
    ]
    const store = mockStore({
      config: {
        token: { access_token: 'wtw45CmyEuh4P621IDVxWkgVr5QwTg3wXEc4Z7Cv' }
      },
      years: []
    })

    return (
      store
        .dispatch(getYear(2016))
        //This calls fetch 4 times, once for each season
        .then(() => {
          // return of async actions
          expect(store.getActions()).toEqual(expectedActions)
        })
    )
  })
})

Reset mocks between tests with fetch.resetMocks

fetch.resetMocks resets the fetch mock to give fresh mock data in between tests. It only resets the fetch calls as to not disturb any other mocked functionality.

describe('getYear action creator', () => {
  beforeEach(() => {
    fetch.resetMocks()
  })

  it('mocks each test independently', async () => {
    fetch.once(JSON.stringify([{ name: 'naruto', average_score: 79 }]))
    // ... first test's fetches and assertions
  })

  it('starts from a clean slate', async () => {
    // fetch.mock.calls is empty again here thanks to resetMocks
    fetch.once(JSON.stringify([{ name: 'bleach', average_score: 68 }]))
    // ... second test's fetches and assertions
  })
})

(Remember: if your Jest config has resetMocks: true, see the gotcha at the top — Jest's automatic reset clears the mock implementation too, which is more than fetch.resetMocks() does.)

Using fetch.mock to inspect the mock state of each fetch call

fetch.mock by default uses Jest's mocking functions. Therefore you can make assertions on the mock state. In this example we have an arbitrary function that makes a different fetch request based on the argument you pass to it. In our test, we run Jest's beforeEach() and make sure to reset our mock before each it() block as we will make assertions on the arguments we are passing to fetch(). The most used property is the fetch.mock.calls array. It can give you information on each call, and their arguments which you can use for your expect() calls. Jest also comes with some nice aliases for the most used ones.

// api.js

import 'cross-fetch'

export function APIRequest(who) {
  if (who === 'facebook') {
    return fetch('https://facebook.com')
  } else if (who === 'twitter') {
    return fetch('https://twitter.com')
  } else {
    return fetch('https://google.com')
  }
}
// api.test.js
import { APIRequest } from './api'

describe('testing api', () => {
  beforeEach(() => {
    fetch.resetMocks()
  })

  it('calls google by default', () => {
    fetch.mockResponse(JSON.stringify({ secret_data: '12345' }))
    APIRequest()

    expect(fetch.mock.calls.length).toEqual(1)
    expect(fetch.mock.calls[0][0]).toEqual('https://google.com')
  })

  it('calls facebook', () => {
    fetch.mockResponse(JSON.stringify({ secret_data: '12345' }))
    APIRequest('facebook')

    expect(fetch.mock.calls.length).toEqual(1)
    expect(fetch.mock.calls[0][0]).toEqual('https://facebook.com')
  })

  it('calls twitter', () => {
    fetch.mockResponse(JSON.stringify({ secret_data: '12345' }))
    APIRequest('twitter')

    expect(fetch).toBeCalled() // alias for expect(fetch.mock.calls.length).toEqual(1);
    expect(fetch).toBeCalledWith('https://twitter.com') // alias for expect(fetch.mock.calls[0][0]).toEqual();
  })
})

Using functions to mock slow servers

By default you will want to have your fetch mock return immediately. However if you have some custom logic that needs to test for slower servers, you can do this by passing it a function and returning a promise when your function resolves

// api.test.js
import { request } from './api'

describe('testing timeouts', () => {
  it('resolves with function and timeout', async () => {
    fetch.mockResponseOnce(
      () =>
        new Promise(resolve => setTimeout(() => resolve({ body: 'ok' }), 100))
    )
    const response = await request()
    expect(response).toEqual('ok')
  })
})

Conditional Mocking

In some test scenarios, you may want to temporarily disable (or enable) mocking for all requests or the next (or a certain number of) request(s). You may want to only mock fetch requests to some URLs that match a given request path while in others you may want to mock all requests except those matching a given request path. You may even want to conditionally mock based on request headers.

The conditional mock functions cause jest-fetch-mock to pass fetches through to the concrete fetch implementation conditionally. Calling fetch.dontMock, fetch.doMock, fetch.doMockIf or fetch.dontMockIf overrides the default behavior of mocking/not mocking all requests. fetch.dontMockOnce, fetch.doMockOnce, fetch.doMockOnceIf and fetch.dontMockOnceIf only overrides the behavior for the next call to fetch, then returns to the default behavior (either mocking all requests or mocking the requests based on the last call to fetch.dontMock, fetch.doMock, fetch.doMockIf and fetch.dontMockIf).

Calling fetch.resetMocks() will return to the default behavior of mocking all fetches with a text response of empty string.

  • fetch.dontMock() - Change the default behavior to not mock any fetches until fetch.resetMocks() or fetch.doMock() is called
  • fetch.doMock(bodyOrFunction?, responseInit?) - Reverses fetch.dontMock(). This is the default state after fetch.resetMocks()
  • fetch.dontMockOnce() - For the next fetch, do not mock then return to the default behavior for subsequent fetches. Can be chained.
  • fetch.doMockOnce(bodyOrFunction?, responseInit?) or fetch.mockOnce - For the next fetch, mock the response then return to the default behavior for subsequent fetches. Can be chained.
  • fetch.doMockIf(urlOrPredicate, bodyOrFunction?, responseInit?):fetch or fetch.mockIf - causes all fetches to be not be mocked unless they match the given string/RegExp/predicate (i.e. "only mock 'fetch' if the request is for the given URL otherwise, use the real fetch implementation")
  • fetch.dontMockIf(urlOrPredicate, bodyOrFunction?, responseInit?):fetch - causes all fetches to be mocked unless they match the given string/RegExp/predicate (i.e. "don't mock 'fetch' if the request is for the given URL, otherwise mock the request")
  • fetch.doMockOnceIf(urlOrPredicate, bodyOrFunction?, responseInit?):fetch or fetch.mockOnceIf - causes the next fetch to be mocked if it matches the given string/RegExp/predicate. Can be chained. (i.e. "only mock 'fetch' if the next request is for the given URL otherwise, use the default behavior")
  • fetch.dontMockOnceIf(urlOrPredicate):fetch - causes the next fetch to be not be mocked if it matches the given string/RegExp/predicate. Can be chained. (i.e. "don't mock 'fetch' if the next request is for the given URL, otherwise use the default behavior")
  • fetch.isMocking(input, init):boolean - test utility function to see if the given url/request would be mocked. This is not a read only operation and any "MockOnce" will evaluate (and return to the default behavior)

For convenience, all the conditional mocking functions also accept optional parameters after the 1st parameter that call mockResponse or mockResponseOnce respectively. This allows you to conditionally mock a response in a single call.

Conditional mocking examples

describe('conditional mocking', () => {
  const realResponse = 'REAL FETCH RESPONSE'
  const mockedDefaultResponse = 'MOCKED DEFAULT RESPONSE'
  const testUrl = defaultRequestUri
  let realFetchBackup
  beforeEach(() => {
    fetch.resetMocks()
    fetch.mockResponse(mockedDefaultResponse)
    // stub the "real" side by swapping the passthrough target
    realFetchBackup = fetchMock.realFetch
    fetchMock.realFetch = jest.fn(async () => new Response(realResponse))
  })

  afterEach(() => {
    fetchMock.realFetch = realFetchBackup
  })

  const expectMocked = async (uri, response = mockedDefaultResponse) => {
    return expect(request(uri)).resolves.toEqual(response)
  }
  const expectUnmocked = async uri => {
    return expect(request(uri)).resolves.toEqual(realResponse)
  }

  describe('doMockIf', () => {
    it("doesn't mock normally", async () => {
      fetch.doMockIf('http://foo')
      await expectUnmocked()
      await expectUnmocked()
    })
    it('mocks when matches string', async () => {
      fetch.doMockIf(testUrl)
      await expectMocked()
      await expectMocked()
    })
    it('mocks when matches regex', async () => {
      fetch.doMockIf(new RegExp(testUrl))
      await expectMocked()
      await expectMocked()
    })
    it('mocks when matches predicate', async () => {
      fetch.doMockIf(input => input.url === testUrl)
      await expectMocked()
      await expectMocked()
    })
  })

  describe('dontMockIf', () => {
    it('mocks normally', async () => {
      fetch.dontMockIf('http://foo')
      await expectMocked()
      await expectMocked()
    })
    it('doesnt mock when matches string', async () => {
      fetch.dontMockIf(testUrl)
      await expectUnmocked()
      await expectUnmocked()
    })
  })

  describe('dont/do mock', () => {
    test('dontMock', async () => {
      fetch.dontMock()
      await expectUnmocked()
      await expectUnmocked()
    })
    test('dontMockOnce', async () => {
      fetch.dontMockOnce()
      await expectUnmocked()
      await expectMocked()
    })
    test('doMock', async () => {
      fetch.dontMock()
      fetch.doMock()
      await expectMocked()
      await expectMocked()
    })
    test('doMockOnce', async () => {
      fetch.dontMock()
      fetch.doMockOnce()
      await expectMocked()
      await expectUnmocked()
    })
  })
})

For a longer, exhaustive example of interleaved once/if conditional mocks, see tests/test.js.

Recipes and common gotchas

Respond with JSON — stringify it

mockResponse takes a body string. Passing an object directly silently becomes "[object Object]" and then response.json() fails:

fetch.mockResponse(JSON.stringify({ foo: 'bar' })) // ✅
fetch.mockResponse({ foo: 'bar' })                 // ❌ "[object Object]"

One mock per endpoint

The cleanest way to route different URLs to different responses (#126):

fetch.mockResponse(async (req) => {
  const url = new URL(req.url)
  switch (url.pathname) {
    case '/users':
      return JSON.stringify([{ id: 1 }])
    case '/teams':
      return JSON.stringify([{ id: 42 }])
    default:
      return { status: 404, body: 'Not Found' }
  }
})

Or scope mocking to one host and leave everything else real with fetch.mockIf(/^https:\/\/api\.example\.com\//, handler).

Empty bodies and response.json()

The default mock response is an empty string, and res.json() on an empty body rejects ("Unexpected end of JSON input") — browsers are no more lenient (#63). If the code under test always calls .json(), always mock a JSON body — at minimum fetch.mockResponse('{}').

ok and status

response.ok is derived automatically: it is true for status in the 200–299 range (#119). To test an error path, just set the status:

fetch.mockResponseOnce('server blew up', { status: 503 })

Mocking ponyfill imports (cross-fetch, node-fetch)

Code that imports fetch as a module (import fetch from 'cross-fetch') bypasses the global mock. Redirect the module to the mock instead (#122):

// setupJest.js
require('jest-fetch-mock').enableMocks()
jest.setMock('cross-fetch', fetchMock) // and/or 'node-fetch' (done automatically for node-fetch)

enableMocks() already does this for node-fetch; add a jest.setMock line per additional ponyfill module your code imports.

"jest is not defined"

jest-fetch-mock calls jest.fn() on import, so it can only be imported where Jest's globals exist: test files, setupFiles, or setupFilesAfterEnv — not in globalSetup, custom sequencers, or plain Node scripts (#104). For injectGlobals: false setups, use createFetchMock from jest-fetch-mock/factory, which imports cleanly anywhere. If the error appears after a dependency update, also try clearing the watcher/cache: npx jest --clearCache.

Binary responses

Pass a Response with a Buffer body (new in 3.2.0):

fetch.mockResponseOnce(new Response(Buffer.from([0x89, 0x50, 0x4e, 0x47])))
const buf = await (await fetch('https://example.com/img.png')).arrayBuffer()

License

MIT — see LICENSE.md.