diff --git a/src/scriptlets/prevent-fetch.js b/src/scriptlets/prevent-fetch.js index f376654db..ae8d9d7ab 100644 --- a/src/scriptlets/prevent-fetch.js +++ b/src/scriptlets/prevent-fetch.js @@ -42,6 +42,7 @@ import { * - `emptyObj` - empty object * - `emptyArr` - empty array * - responseType - optional, string for defining response type, defaults to `default`. Possible values: + * - default * - opaque * * > Usage with no arguments will log fetch calls to browser console; @@ -104,9 +105,11 @@ export function preventFetch(source, propsToMatch, responseBody = 'emptyObj', re return; } - let allowedResponseType; - if (responseType === 'default' || responseType === 'opaque') { - allowedResponseType = responseType; + // Skip disallowed response types + if (!(responseType === 'default' || responseType === 'opaque')) { + // eslint-disable-next-line no-console + console.log(`Invalid parameter: ${responseType}`); + return; } const handlerWrapper = (target, thisArg, args) => { @@ -139,7 +142,7 @@ export function preventFetch(source, propsToMatch, responseBody = 'emptyObj', re if (shouldPrevent) { hit(source); - return noopPromiseResolve(strResponseBody, fetchData.url, allowedResponseType); + return noopPromiseResolve(strResponseBody, fetchData.url, responseType); } return Reflect.apply(target, thisArg, args); diff --git a/tests/scriptlets/prevent-fetch.test.js b/tests/scriptlets/prevent-fetch.test.js index cc4935230..4233d71df 100644 --- a/tests/scriptlets/prevent-fetch.test.js +++ b/tests/scriptlets/prevent-fetch.test.js @@ -287,4 +287,48 @@ if (!isSupported) { assert.strictEqual(window.hit, 'FIRED', 'hit function fired'); done(); }); + + test('simple fetch - valid response type', async (assert) => { + const OPAQUE_RESPONSE_TYPE = 'opaque'; + const INPUT_JSON_PATH = `${FETCH_OBJECTS_PATH}/test01.json`; + const init = { + method: 'GET', + }; + + runScriptlet(name, ['*', '', OPAQUE_RESPONSE_TYPE]); + const done = assert.async(); + + const response = await fetch(INPUT_JSON_PATH, init); + + assert.strictEqual(response.type, OPAQUE_RESPONSE_TYPE, 'Response type is set'); + assert.strictEqual(window.hit, 'FIRED', 'hit function fired'); + done(); + }); + + test('simple fetch - invalid response type', async (assert) => { + const INVALID_RESPONSE_TYPE = 'invalid_type'; + const BASIC_RESPONSE_TYPE = 'basic'; + const INPUT_JSON_PATH = `${FETCH_OBJECTS_PATH}/test01.json`; + const init = { + method: 'GET', + }; + + const expectedJson = { + a1: 1, + b2: 'test', + c3: 3, + }; + + runScriptlet(name, ['*', '', INVALID_RESPONSE_TYPE]); + const done = assert.async(); + + const response = await fetch(INPUT_JSON_PATH, init); + const actualJson = await response.json(); + + assert.deepEqual(actualJson, expectedJson, 'Request is not modified'); + + assert.strictEqual(response.type, BASIC_RESPONSE_TYPE, 'Response type is not modified'); + assert.strictEqual(window.hit, undefined, 'hit function fired'); + done(); + }); }