scratch-storage/test/mocks/mockFetch.js
Christopher Willis-Ford fd6f3a166a refactor: use cross-fetch instead of node-fetch
Previously, we had Webpack's ProvidePlugin injecting `node-fetch` as a
polyfill into Node builds, and web builds just relied on the `fetch`
built into the browser (if it's there).

Now, we use `cross-fetch` everywhere, and as a ponyfill instead of a
polyfill. This broke the unit tests in `fetch-tool.js` because they were
overriding `global.fetch` to mock `node-fetch`. Now, those tests use
`tap.mock` to mock `cross-fetch`. Of course, `tap.mock` didn't exist in
the old version of `node-tap`, so I also upgraded that.
2023-03-09 13:39:24 -08:00

36 lines
982 B
JavaScript

const TextEncoder = require('util').TextEncoder;
const successText = 'successful response';
/**
* Mock the 'fetch' method from browsers. Ignores the 'options' parameter.
* @param {string} resource - the (mock) resource to fetch, which will determine the response.
* @returns {Promise} - a promise for a Response-like object. Does not fully implement Response.
*/
const mockFetch = resource => {
switch (resource) {
case '200':
return Promise.resolve({
ok: true,
text: () => Promise.resolve(successText),
arrayBuffer: () => Promise.resolve(new TextEncoder().encode(successText))
});
case '404':
return Promise.resolve({
ok: false,
status: 404
});
case '500':
return Promise.resolve({
ok: false,
status: 500
});
default:
throw new Error('unimplemented');
}
};
module.exports = {
mockFetch,
successText
};