Skip to content

Commit

Permalink
add tests stub & fix logging logic
Browse files Browse the repository at this point in the history
  • Loading branch information
stanislav-atr committed Oct 25, 2022
1 parent acef717 commit 039c5b0
Show file tree
Hide file tree
Showing 4 changed files with 111 additions and 11 deletions.
1 change: 1 addition & 0 deletions src/scriptlets/scriptlets-list.js
Original file line number Diff line number Diff line change
Expand Up @@ -49,3 +49,4 @@ export * from './prevent-refresh';
export * from './prevent-element-src-loading';
export * from './no-topics';
export * from './xml-prune';
export * from './trusted-replace-fetch-response';
25 changes: 14 additions & 11 deletions src/scriptlets/trusted-replace-fetch-response.js
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ import {
* **Examples**
* 1. Log all fetch calls
* ```
* example.org#%#//scriptlet('prevent-fetch')
* example.org#%#//scriptlet('trusted-replace-fetch-response')
* ```
*
* 2. Replace response text content of fetch requests with specific url
Expand All @@ -74,7 +74,7 @@ import {
* ```
*/
/* eslint-enable max-len */
export function trustedReplaceFetchResponse(source, pattern = '', replacement = '', propsToMatch = '') {
export function trustedReplaceFetchResponse(source, pattern = '', replacement = '', propsToMatch) {
// do nothing if browser does not support fetch or Proxy (e.g. Internet Explorer)
// https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy
Expand All @@ -83,38 +83,41 @@ export function trustedReplaceFetchResponse(source, pattern = '', replacement =
|| typeof Response === 'undefined') {
return;
}
debugger;
const shouldLog = typeof pattern === 'undefined';

if (typeof pattern === 'undefined' || typeof replacement === 'undefined') {
if (!shouldLog && (pattern === '' || typeof replacement === 'undefined')) {
return;
}

// eslint-disable-next-line no-console
const log = console.log.bind(console);
const nativeFetch = fetch;

let shouldPrevent = false;
let shouldReplace = false;
let fetchData;

const handlerWrapper = async (target, thisArg, args) => {
fetchData = getFetchData(args);

if (typeof propsToMatch === 'undefined') {
if (shouldLog) {
// log if no propsToMatch given
const logMessage = `log: fetch( ${objectToString(fetchData)} )`;
log(source, logMessage);
hit(source);
} else if (propsToMatch === '' || propsToMatch === getWildcardSymbol()) {
// prevent all fetch calls
shouldPrevent = true;
// match all fetch calls
shouldReplace = true;
} else {
const parsedData = parseMatchProps(propsToMatch);
if (!validateParsedData(parsedData)) {
// eslint-disable-next-line no-console
console.log(`Invalid parameter: ${propsToMatch}`);
shouldPrevent = false;
shouldReplace = false;
} else {
const matchData = getMatchPropsData(parsedData);
// prevent only if all props match
shouldPrevent = Object.keys(matchData)
// request matches only if all props match
shouldReplace = Object.keys(matchData)
.every((matchKey) => {
const matchValue = matchData[matchKey];
return Object.prototype.hasOwnProperty.call(fetchData, matchKey)
Expand All @@ -123,7 +126,7 @@ export function trustedReplaceFetchResponse(source, pattern = '', replacement =
}
}

if (!shouldPrevent) {
if (!shouldReplace) {
return Reflect.apply(target, thisArg, args);
}

Expand Down
1 change: 1 addition & 0 deletions tests/scriptlets/index.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -46,3 +46,4 @@ import './prevent-element-src-loading.test';
import './no-topics.test';
import './xml-prune.test';
import './trusted-click-element.test';
import './trusted-replace-fetch-response.test';
95 changes: 95 additions & 0 deletions tests/scriptlets/trusted-replace-fetch-response.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
/* eslint-disable no-underscore-dangle, no-console */
import { runScriptlet, clearGlobalProps } from '../helpers';
import { startsWith } from '../../src/helpers/string-utils';
import { isEmptyObject } from '../../src/helpers/object-utils';

const { test, module } = QUnit;
const name = 'trusted-replace-fetch-response';

const FETCH_OBJECTS_PATH = './test-files';
const nativeFetch = fetch;
const nativeConsole = console.log;
const nativeResponseJson = Response.prototype.json;

const beforeEach = () => {
window.__debug = () => {
window.hit = 'FIRED';
};
};

const afterEach = () => {
clearGlobalProps('hit', '__debug');
fetch = nativeFetch; // eslint-disable-line no-global-assign
console.log = nativeConsole;
Response.prototype.json = nativeResponseJson;
};

module(name, { beforeEach, afterEach });

const isSupported = typeof fetch !== 'undefined' && typeof Proxy !== 'undefined' && typeof Response !== 'undefined';

if (!isSupported) {
test('unsupported', (assert) => {
assert.ok(true, 'Browser does not support it');
});
} else {
// test('No arguments, logging', async (assert) => {
// const INPUT_JSON_PATH = `${FETCH_OBJECTS_PATH}/test01.json`;
// const TEST_METHOD = 'POST';
// const init = {
// method: TEST_METHOD,
// };
// const expectedJson = {
// a1: 1,
// b2: 'test',
// c3: 3,
// };
// const done = assert.async();

// // mock console.log function for log checking
// console.log = function log(input) {
// if (input.indexOf('trace') > -1) {
// return;
// }
// // eslint-disable-next-line max-len
// const EXPECTED_LOG_STR_START = `fetch( url:"${INPUT_JSON_PATH}" method:"${TEST_METHOD}"`;
// assert.ok(startsWith(input, EXPECTED_LOG_STR_START), 'console.hit input');
// };

// // no args -> just logging, no preventing
// runScriptlet(name);

// const response = await fetch(INPUT_JSON_PATH, init);
// const actualJson = await response.json();

// assert.strictEqual(window.hit, 'FIRED', 'hit function fired');
// assert.deepEqual(actualJson, expectedJson);
// done();
// });

// test('Pattern(string) & replacement, match all requests', async (assert) => {
// const INPUT_JSON_PATH_1 = `${FETCH_OBJECTS_PATH}/test01.json`;
// const inputRequest1 = new Request(INPUT_JSON_PATH_1);

// const INPUT_JSON_PATH_2 = `${FETCH_OBJECTS_PATH}/test02.json`;
// const init2 = {
// method: 'GET',
// };

// const PATTERN = 'test';
// const REPLACEMENT = 'REPLACEMENT';

// runScriptlet(name, [PATTERN, REPLACEMENT, '*']);
// const done1 = assert.async();
// // const done2 = assert.async();

// const response1 = await fetch(inputRequest1);
// const parsedData1 = await response1.text();

// assert.notOk(parsedData1.includes(PATTERN), 'Pattern is removed');
// assert.ok(parsedData1.includes(REPLACEMENT), 'Replacement is set');
// assert.strictEqual(window.hit, 'FIRED', 'hit function fired');
// done1();
// clearGlobalProps('hit');
// });
}

0 comments on commit 039c5b0

Please sign in to comment.