Security News
RubyGems.org Adds New Maintainer Role
RubyGems.org has added a new "maintainer" role that allows for publishing new versions of gems. This new permission type is aimed at improving security for gem owners and the service overall.
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
npm 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')
All the built in jest function inspection assertions can be used, e.g. expect(fetchMock).toHaveBeenCalledWith('http://example.com')
.
fetch.mockClear()
can be used to reset the call history
fetch.mockReset()
can be used to remove all configured mocks
All other jest methods for configuring mock functions are disabled as fetch-mock's own methods should always be used
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 methods
These would also be useful jest extensions:
toHaveFetched
toHaveRespondedWith(object | status | string )
(using fetch-mock internals to convert to a response config, then use jest objectMatching)FAQs
Jest wrapper for fetch-mock, a comprehensive stub for fetch
The npm package fetch-mock-jest receives a total of 30,603 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.
Security News
RubyGems.org has added a new "maintainer" role that allows for publishing new versions of gems. This new permission type is aimed at improving security for gem owners and the service overall.
Security News
Node.js will be enforcing stricter semver-major PR policies a month before major releases to enhance stability and ensure reliable release candidates.
Security News
Research
Socket's threat research team has detected five malicious npm packages targeting Roblox developers, deploying malware to steal credentials and personal data.