Socket
Socket
Sign inDemoInstall

fetch-mock

Package Overview
Dependencies
2
Maintainers
1
Versions
213
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

fetch-mock


Version published
Weekly downloads
647K
decreased by-8.08%
Maintainers
1
Created
Weekly downloads
 

Package description

What is fetch-mock?

fetch-mock is a library for mocking HTTP requests made using the Fetch API. It allows developers to simulate different responses and behaviors for fetch calls, which is particularly useful for testing and development purposes.

What are fetch-mock's main functionalities?

Mocking a simple GET request

This feature allows you to mock a simple GET request. The code sample demonstrates how to mock a GET request to 'https://api.example.com/data' and return a JSON object with sample data.

const fetchMock = require('fetch-mock');
fetchMock.get('https://api.example.com/data', { data: 'sample data' });

fetch('https://api.example.com/data')
  .then(response => response.json())
  .then(data => console.log(data));

Mocking a POST request with specific body

This feature allows you to mock a POST request with a specific request body. The code sample demonstrates how to mock a POST request to 'https://api.example.com/submit' and return different responses based on the request body.

const fetchMock = require('fetch-mock');
fetchMock.post('https://api.example.com/submit', (url, options) => {
  if (options.body === JSON.stringify({ key: 'value' })) {
    return { status: 'success' };
  } else {
    return { status: 'error' };
  }
});

fetch('https://api.example.com/submit', {
  method: 'POST',
  body: JSON.stringify({ key: 'value' })
})
  .then(response => response.json())
  .then(data => console.log(data));

Mocking with delay

This feature allows you to mock a request with a delay. The code sample demonstrates how to mock a GET request to 'https://api.example.com/delayed' and return a response after a 1-second delay.

const fetchMock = require('fetch-mock');
fetchMock.get('https://api.example.com/delayed', new Promise(resolve => setTimeout(() => resolve({ data: 'delayed data' }), 1000)));

fetch('https://api.example.com/delayed')
  .then(response => response.json())
  .then(data => console.log(data));

Mocking with different response statuses

This feature allows you to mock requests with different HTTP response statuses. The code sample demonstrates how to mock a GET request to 'https://api.example.com/not-found' and return a 404 status.

const fetchMock = require('fetch-mock');
fetchMock.get('https://api.example.com/not-found', 404);

fetch('https://api.example.com/not-found')
  .then(response => {
    if (!response.ok) {
      throw new Error('Network response was not ok');
    }
    return response.json();
  })
  .catch(error => console.error('Fetch error:', error));

Other packages similar to fetch-mock

Readme

Source

fetch-mock Build Status

Mock http requests made using fetch (or isomorphic-fetch)

notes

  • When using isomorphic-fetch or node-fetch fetch should be added as a global
  • fetch-mock doesn't declare fetch or Promise as dependencies; as you're testing fetch it's assumed you're already taking care of these globals

var fetchMock = require('fetch-mock');

// Set up some routes you will always want to mock
// Accepts an array of config objects or three parameters,
// name, matcher and response, to add a single route
fetchMock.registerRoute([
 {
	 name: 'session',
	 matcher: 'https://sessionservice.host.com',
	 response: {
	 	body: 'user-12345',
	 	// opts is as expected by https://github.com/bitinn/node-fetch/blob/master/lib/response.js
	 	// headers should be passed as an object literal (fetch-mock will convert it into a Headers instance)
	 	// status defaults to 200
	 	opts: {
	 		headers: {
	 			'x-status': 'unsubscribed'
	 		},
	 		status: 401
	 	}
	 }
 },
 {
	name: 'geo',
	matcher: /^https\:\/\/geoservice\.host\.com/,
	// objects will be converted to strings using JSON.stringify before being returned
	response: {
	 	body: {
			country: 'uk'
		}
	}
 }
])


it('should do A', function () {
	fetchMock.mock({
		// none: all unmatched calls get sent straight through to the default fetch
		// bad: all unmatched calls result in a rejected promise
		// good: all unmatched calls result in a resolved promise with a 200 status
		greed: 'none' 
	});
	
	thingToTest.exec();

	// returns an array of calls to the session service, 
	// each item in the array is an array of the arguments passed to fetch
	// similar to sinon.spy.args
	fetchMock.calls('session') // non empty array
	fetchMock.called('geo') // Boolean

	// reset all call logs
	fetchMock.reset()

	fetchMock.calls('session') // undefined
	fetchMock.called('geo') // false
	
	// fetch itself is just an ordinary sinon.stub
	fetch.calledWith('thing')

	// restores fetch and resets all data
	fetchMock.restore();
})

describe('content', function () {
	before(function () {
		// register an additional route, this one has a more complex matching rule
		fetchMock.registerRoute('content', function (url, opts) {
			return opts.headers.get('x-api-key') && url.test(/^https\:\/\/contentservice\.host\.com/);
		}, {body: 'I am an article'});
	});

	after(function () {
		// I wonder what this does??
		fetchMock.unregisterRoute('content');
	})

	it('should do B', function () {
		
		
		fetchMock.mock({
			// you can choose to mock a subset of the registered routes
			// and even add one to be mocked for this test only 
			// - the route will exist until fetchMock.restore() is called
			routes: ['session', 'content', {
			 name: 'enhanced-content',
			 matcher: /^https\:\/\/enhanced-contentservice\.host\.com/,
			 // responses can be contextual depending on the request
			 // url and opts parameters are exactly what would be passed to fetch
			 response: function (url, opts) {
				return {body: 'enhanced-article-' + url.split('article-id/')[1]};
			 }
			}]
		});
		
		thingToTest.exec();

		fetchMock.calls('content') // non empty array
		fetchMock.called('enhanced-content') // Boolean
		
		// restores fetch and resets all data
		fetchMock.restore();
	})

	it('should do C', function () {
		
		
		fetchMock.mock({
			// you can override the response for a service for this test only
			// this means e.g. you can configure an authentication service to return 
			// a valid user normally, but only return invalid for the one test
			// where you're testing authentication
			responses: {
				'session': 'invalid-user'
			}
		});
		
		thingToTest.exec();

		// restores fetch and resets all data
		fetchMock.restore();
	})

});

Keywords

FAQs

Last updated on 04 May 2015

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap

Packages

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc