Research
Security News
Malicious npm Packages Inject SSH Backdoors via Typosquatted Libraries
Socket’s threat research team has detected six malicious npm packages typosquatting popular libraries to insert SSH backdoors.
fetch-mock-jest
Advanced tools
fetch-mock-jest is a library that allows you to mock fetch calls in your Jest tests. It provides a simple and powerful way to simulate different responses from the fetch API, making it easier to test your code's behavior under various conditions.
Mocking a simple fetch request
This feature allows you to mock a simple fetch request and provide a predefined response. In this example, the fetch call to '/api/data' will return a JSON object with data '12345'.
const fetchMock = require('fetch-mock-jest');
fetchMock.mockResponseOnce(JSON.stringify({ data: '12345' }));
fetch('/api/data')
.then(res => res.json())
.then(data => {
console.log(data); // { data: '12345' }
});
Mocking multiple fetch requests
This feature allows you to mock multiple fetch requests in sequence. Each call to fetch will return the next mocked response in the order they were defined.
const fetchMock = require('fetch-mock-jest');
fetchMock
.mockResponseOnce(JSON.stringify({ data: 'first' }))
.mockResponseOnce(JSON.stringify({ data: 'second' }));
fetch('/api/first')
.then(res => res.json())
.then(data => {
console.log(data); // { data: 'first' }
});
fetch('/api/second')
.then(res => res.json())
.then(data => {
console.log(data); // { data: 'second' }
});
Mocking fetch with different HTTP methods
This feature allows you to mock fetch requests based on different HTTP methods. In this example, a POST request to '/api/data' will return a specific response, while other methods will return a different response.
const fetchMock = require('fetch-mock-jest');
fetchMock.mockResponseOnce((req) => {
if (req.method === 'POST') {
return JSON.stringify({ message: 'Post request received' });
}
return JSON.stringify({ message: 'Other request' });
});
fetch('/api/data', { method: 'POST' })
.then(res => res.json())
.then(data => {
console.log(data); // { message: 'Post request received' }
});
Mocking fetch with different status codes
This feature allows you to mock fetch requests with different HTTP status codes. In this example, a fetch call to '/api/not-found' will return a 404 status, simulating a 'Not Found' error.
const fetchMock = require('fetch-mock-jest');
fetchMock.mockResponseOnce('', { status: 404 });
fetch('/api/not-found')
.then(res => {
if (!res.ok) {
throw new Error('Not Found');
}
return res.json();
})
.catch(error => {
console.error(error); // Error: Not Found
});
jest-fetch-mock is a library that provides a similar functionality to fetch-mock-jest, allowing you to mock fetch calls in Jest tests. It offers a simple API to mock fetch responses and is well-integrated with Jest's mocking capabilities. Compared to fetch-mock-jest, jest-fetch-mock is more focused on Jest and provides a more straightforward API for common use cases.
nock is a powerful HTTP mocking library for Node.js that allows you to intercept and mock HTTP requests. While it is not specifically designed for fetch, it can be used to mock fetch requests by intercepting the underlying HTTP calls. Nock provides a rich set of features for mocking and asserting HTTP requests, making it a versatile tool for testing HTTP interactions.
msw (Mock Service Worker) is a library for mocking network requests in both browser and Node.js environments. It uses Service Workers to intercept and mock HTTP requests, providing a seamless way to test network interactions. MSW offers a declarative API for defining request handlers and supports a wide range of use cases, including fetch requests. Compared to fetch-mock-jest, MSW provides a more comprehensive solution for mocking network requests across different environments.
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:
fetch-mock-jest requires the following to run:
node-fetch
is not included as a dependency of fetch-mock
.fetch
API either natively or via a polyfill/ponyfillnpm install -D fetch-mock-jest
const fetchMock = require('fetch-mock-jest')
jest.mock('node-fetch', () => require('fetch-mock-jest').sandbox())
const fetchMock = require('node-fetch')
Please refer to the fetch-mock documentation and cheatsheet
All jest methods for configuring mock functions are disabled as fetch-mock's own methods should always be used
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)
filter
and options
are the same as those used by fetch-mock
's inspection methodsFetched
replaced by any of the following verbs to scope to a particular method: + Got + Posted + Put + Deleted + FetchedHead + Patchede.g. expect(fetchMock).toHaveLastPatched(filter, options)
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
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();
});
FAQs
Jest wrapper for fetch-mock, a comprehensive stub for fetch
The npm package fetch-mock-jest receives a total of 165,860 weekly downloads. As such, fetch-mock-jest popularity was classified as popular.
We found that fetch-mock-jest demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
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.
Research
Security News
Socket’s threat research team has detected six malicious npm packages typosquatting popular libraries to insert SSH backdoors.
Security News
MITRE's 2024 CWE Top 25 highlights critical software vulnerabilities like XSS, SQL Injection, and CSRF, reflecting shifts due to a refined ranking methodology.
Security News
In this segment of the Risky Business podcast, Feross Aboukhadijeh and Patrick Gray discuss the challenges of tracking malware discovered in open source softare.