Git Product home page Git Product logo

fetch-mock-jest's Introduction

fetch-mock-jest

Wrapper around fetch-mock - a comprehensive, isomorphic mock for the fetch api - which provides an interface that is more idiomatic when working in jest.

The example at the bottom of this readme demonstrates the intuitive API, but shows off only a fraction of fetch-mock's functionality. Features include:

  • mocks most of the fetch API spec, even advanced behaviours such as streaming and aborting
  • declarative matching for most aspects of a http request, including url, headers, body and query parameters
  • shorthands for the most commonly used features, such as matching a http method or matching one fetch only
  • support for delaying responses, or using your own async functions to define custom race conditions
  • can be used as a spy to observe real network requests
  • isomorphic, and supports either a global fetch instance or a locally required instanceg

Installation

npm install -D fetch-mock-jest

global fetch

const fetchMock = require('fetch-mock-jest')

node-fetch

jest.mock('node-fetch', () => require('fetch-mock-jest').sandbox())
const fetchMock = require('node-fetch')

API

Setting up mocks

Please refer to the fetch-mock documentation

All jest methods for configuring mock functions are disabled as fetch-mock's own methods should always be used

Inspecting mocks

All the built in jest function inspection assertions can be used, e.g. expect(fetchMock).toHaveBeenCalledWith('http://example.com').

fetchMock.mock.calls and fetchMock.mock.results are also exposed, giving access to manually inspect the calls.

The following custom jest expectation methods, proxying through to fetch-mock's inspection methods are also available. They can all be prefixed with the .not helper for negative assertions.

  • expect(fetchMock).toHaveFetched(filter, options)
  • expect(fetchMock).toHaveLastFetched(filter, options)
  • expect(fetchMock).toHaveNthFetched(n, filter, options)
  • expect(fetchMock).toHaveFetchedTimes(n, filter, options)
  • expect(fetchMock).toBeDone(filter)

Notes

  • filter and options are the same as those used by fetch-mock's inspection methods
  • The obove methods can have Fetched replaced by any of the following verbs to scope to a particular method: + Got + Posted + Put + Deleted + FetchedHead + Patched

e.g. expect(fetchMock).toHaveLastPatched(filter, options)

Tearing down mocks

fetchMock.mockClear() can be used to reset the call history

fetchMock.mockReset() can be used to remove all configured mocks

Please report any bugs in resetting mocks on the issues board

Example

const fetchMock = require('fetch-mock-jest');
const userManager = require('../src/user-manager');

test(async () => {
	const users = [{ name: 'bob' }];
	fetchMock
		.get('http://example.com/users', users)
		.post('http://example.com/user', (url, options) => {
			if (typeof options.body.name === 'string') {
				users.push(options.body);
				return 202;
			}
			return 400;
		})
		.patch(
			{
				url: 'http://example.com/user'
			},
			405
		);

	expect(await userManager.getAll()).toEqual([{ name: 'bob' }]);
	expect(fetchMock).toHaveLastFetched('http://example.com/users
		get');
	await userManager.create({ name: true });
	expect(fetchMock).toHaveLastFetched(
		{
			url: 'http://example.com/user',
			body: { name: true }
		},
		'post'
	);
	expect(await userManager.getAll()).toEqual([{ name: 'bob' }]);
	fetchMock.mockClear();
	await userManager.create({ name: 'sarah' });
	expect(fetchMock).toHaveLastFetched(
		{
			url: 'http://example.com/user',
			body: { name: 'sarah' }
		},
		'post'
	);
	expect(await userManager.getAll()).toEqual([
		{ name: 'bob' },
		{ name: 'sarah' }
	]);
	fetchMock.mockReset();
});

fetch-mock-jest's People

Contributors

wheresrhys avatar dependabot[bot] avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.