How to use intercepted method in wpt

Best JavaScript code snippet using wpt

interceptObject.test.ts

Source:interceptObject.test.ts Github

copy

Full Screen

1/**2 * 'intercepting properties' is to be carried out in the following format:3 * in 'describe':4 * three sets of 'it'5 * 1. have two sets of expect statements. The first testing6 * the globalObj and the second testing the interceptedObject7 * 2. same thing as above but after modification to globalObj8 * 3. same thing as above but after modification to interceptedObject9 *10 * goal here is to make sure the behavior of both objects are the same.11 * *test format exception for testing setters12 *13 *14 * 'mirror properties'15 * in 'describe':16 * two sets of 'it'17 * 1. do modification to globalObj and check for sameness18 * 2. do modification to interceptedObj and check for sameness19 *20 * these are general guidelines. there may be test sets that don't follow this21 * format22 */23import { fakeToString } from './fakeToString';24import { interceptObject } from './interceptObject';25type anyObjType = { [key: string]: any };26describe('interceptObject', () => {27 // globalObj represents window28 // interceptedObj represents pademelonInstance.modifiedWindow29 describe('intercepting properties', () => {30 const globalObj: anyObjType = {};31 describe('immutable value', () => {32 Object.defineProperty(globalObj, 'immutableValue', {33 value: 'unmodifiedValue'34 });35 const modifiedProperties = {};36 Object.defineProperty(modifiedProperties, 'immutableValue', {37 value: 'modifiedValue'38 });39 const interceptedObj = interceptObject(globalObj, { modifiedProperties });40 it('globalObj holds unmodifiedValue and interceptedObj holds modifiedValue', () => {41 expect(globalObj.immutableValue).toEqual('unmodifiedValue');42 expect(interceptedObj.immutableValue).toEqual('modifiedValue');43 });44 it('after modifying globalObj, throws error, and globalObj holds unmodifiedValue and interceptedObject holds modifiedValue', () => {45 expect(() => (globalObj.immutableValue = 'something else')).toThrowError(46 'Cannot assign to read only property'47 );48 expect(globalObj.immutableValue).toEqual('unmodifiedValue');49 expect(interceptedObj.immutableValue).toEqual('modifiedValue');50 });51 it('after modifying interceptedObj, throws error, and globalObj holds unmodifiedValue and interceptedObject holds modifiedValue', () => {52 expect(() => (interceptedObj.immutableValue = 'something else')).toThrowError(53 'trap returned falsish for property'54 );55 expect(globalObj.immutableValue).toEqual('unmodifiedValue');56 expect(interceptedObj.immutableValue).toEqual('modifiedValue');57 });58 });59 describe('mutable value', () => {60 globalObj.mutableValue = 'unmodifiedValue';61 const interceptedObj = interceptObject(globalObj, {62 modifiedProperties: {63 mutableValue: 'modifiedValue'64 }65 });66 it('globalObj holds unmodifiedValue and interceptedObj holds modifiedValue', () => {67 expect(globalObj.mutableValue).toEqual('unmodifiedValue');68 expect(interceptedObj.mutableValue).toEqual('modifiedValue');69 });70 it('after modifying globalObj, globalObj holds change globalObj and interceptedObject holds modifiedValue', () => {71 globalObj.mutableValue = 'change globalObj';72 expect(globalObj.mutableValue).toEqual('change globalObj');73 expect(interceptedObj.mutableValue).toEqual('modifiedValue');74 });75 it('after modifying interceptedObj, globalObj holds change globalObj and interceptedObject holds change interceptedObj', () => {76 interceptedObj.mutableValue = 'change interceptedObj';77 expect(globalObj.mutableValue).toEqual('change globalObj');78 expect(interceptedObj.mutableValue).toEqual('change interceptedObj');79 });80 });81 describe('intercepting getter', () => {82 Object.defineProperty(globalObj, 'immutableGetter', {83 get() {84 return 'unmodifiedValue';85 }86 });87 const interceptedObj = interceptObject(globalObj, {88 modifiedProperties: {89 get immutableGetter() {90 return 'modifiedValue';91 }92 }93 });94 it('globalObj gets unmodifiedValue and interceptedObj gets modifiedValue', () => {95 expect(globalObj.immutableGetter).toEqual('unmodifiedValue');96 expect(interceptedObj.immutableGetter).toEqual('modifiedValue');97 });98 it('after modifying globalObj, throws error, and globalObj holds unmodifiedValue and interceptedObject holds modifiedValue', () => {99 expect(() => (globalObj.immutableGetter = 'something else')).toThrowError('which has only a getter');100 expect(globalObj.immutableGetter).toEqual('unmodifiedValue');101 expect(interceptedObj.immutableGetter).toEqual('modifiedValue');102 });103 it('after modifying interceptedObj, throws error, and globalObj holds unmodifiedValue and interceptedObject holds modifiedValue', () => {104 expect(() => (interceptedObj.immutableGetter = 'something else')).toThrowError(105 'trap returned falsish for property'106 );107 expect(globalObj.immutableGetter).toEqual('unmodifiedValue');108 expect(interceptedObj.immutableGetter).toEqual('modifiedValue');109 });110 });111 describe('intercepting setter', () => {112 const originalSetter = jest.fn();113 const interceptedSetter = jest.fn();114 Object.defineProperty(globalObj, 'immutableSetter', {115 set: originalSetter116 });117 const modifiedProperties = {};118 Object.defineProperty(modifiedProperties, 'immutableSetter', {119 set: interceptedSetter120 });121 const interceptedObj = interceptObject(globalObj, { modifiedProperties });122 it('globalObj setter gets called with setGlobalObj and interceptedObj never gets called', () => {123 globalObj.immutableSetter = 'setGlobalObj';124 expect(originalSetter).toHaveBeenCalledWith('setGlobalObj');125 expect(interceptedSetter).toHaveBeenCalledTimes(0);126 });127 it('globalObj never gets called and interceptedObj gets called with setInterceptedObj', () => {128 interceptedObj.immutableSetter = 'setInterceptedObj';129 expect(originalSetter).toHaveBeenCalledTimes(1); // one from the previous test130 expect(interceptedSetter).toHaveBeenCalledWith('setInterceptedObj');131 });132 });133 describe('intercepting getOwnPropertyDescriptor', () => {134 // gopd = get own property descriptor135 // for this test, we're just going to136 // have globalObj to be a mutable value and137 // interceptedGopd to be an immutable value138 const globalGopd: PropertyDescriptor = {139 writable: true,140 value: 'global',141 configurable: false,142 enumerable: false143 };144 const interceptedGopd: PropertyDescriptor = {145 writable: false,146 value: 'intercept',147 configurable: false,148 enumerable: false149 };150 Object.defineProperty(globalObj, 'gopd', globalGopd);151 const modifiedProperties = {};152 Object.defineProperty(modifiedProperties, 'gopd', interceptedGopd);153 const interceptedObj = interceptObject(globalObj, { modifiedProperties });154 it('globalObj holds global and interceptedObj holds intercept', () => {155 expect(globalObj.gopd).toEqual('global');156 expect(interceptedObj.gopd).toEqual('intercept');157 });158 it('after modifying globalObj, globalObj holds changedglobal and interceptedObject holds intercept', () => {159 globalObj.gopd = 'changedglobal';160 expect(globalObj.gopd).toEqual('changedglobal');161 expect(interceptedObj.gopd).toEqual('intercept');162 });163 it('after modifying interceptedObj, throws error, and globalObj holds changedglobal and interceptedObject holds intercept', () => {164 expect(() => (interceptedObj.gopd = 'changedintercept')).toThrowError(165 'trap returned falsish for property'166 );167 expect(globalObj.gopd).toEqual('changedglobal');168 expect(interceptedObj.gopd).toEqual('intercept');169 });170 it('descriptors should match previously defined descriptors', () => {171 globalObj.gopd = 'global'; // change back to original value172 expect(globalGopd).toStrictEqual(Object.getOwnPropertyDescriptor(globalObj, 'gopd'));173 expect(interceptedGopd).toStrictEqual(Object.getOwnPropertyDescriptor(interceptedObj, 'gopd'));174 });175 });176 });177 describe('mirroring properties', () => {178 const globalObj: anyObjType = {};179 const interceptedObj = interceptObject(globalObj, { useOriginalTarget: false });180 describe('mutable values', () => {181 it('should mutate both when mutating globalObj', () => {182 globalObj.mutateValue = 'mutate globalObj';183 expect(globalObj.mutateValue).toEqual('mutate globalObj');184 expect(interceptedObj.mutateValue).toEqual('mutate globalObj');185 });186 it('should mutate both when mutating interceptedObj', () => {187 interceptedObj.mutateValue = 'mutate interceptedObj';188 expect(globalObj.mutateValue).toEqual('mutate interceptedObj');189 expect(interceptedObj.mutateValue).toEqual('mutate interceptedObj');190 });191 });192 describe('immutable values', () => {193 Object.defineProperty(globalObj, 'immutableValue', {194 writable: false,195 value: 'immutable'196 });197 it('should throw error and not mutate both when mutating globalObj', () => {198 expect(() => (globalObj.immutableValue = 'immutated globalObj')).toThrowError(199 'Cannot assign to read only property'200 );201 expect(globalObj.immutableValue).toEqual('immutable');202 expect(interceptedObj.immutableValue).toEqual('immutable');203 });204 it('should throw error and not mutate both when mutating interceptedObj', () => {205 expect(() => (interceptedObj.immutableValue = 'immutated interceptedObj')).toThrowError(206 'trap returned falsish for property'207 );208 expect(globalObj.immutableValue).toEqual('immutable');209 expect(interceptedObj.immutableValue).toEqual('immutable');210 });211 });212 describe('defineProperty', () => {213 it('should have same descriptor for both when defineProperty on globalObj', () => {214 const descriptor: PropertyDescriptor = {215 writable: false,216 configurable: true,217 enumerable: false,218 value: 'value'219 };220 Object.defineProperty(globalObj, 'defineProperty_globalObj', descriptor);221 expect(Object.getOwnPropertyDescriptor(globalObj, 'defineProperty_globalObj')).toStrictEqual(222 descriptor223 );224 expect(Object.getOwnPropertyDescriptor(interceptedObj, 'defineProperty_globalObj')).toStrictEqual(225 descriptor226 );227 });228 it('should have same descriptor for both when defineProperty on interceptedObject', () => {229 const descriptor: PropertyDescriptor = {230 writable: false,231 configurable: true,232 enumerable: false,233 value: 'value2'234 };235 Object.defineProperty(globalObj, 'defineProperty_interceptedObj', descriptor);236 expect(Object.getOwnPropertyDescriptor(globalObj, 'defineProperty_interceptedObj')).toStrictEqual(237 descriptor238 );239 expect(Object.getOwnPropertyDescriptor(interceptedObj, 'defineProperty_interceptedObj')).toStrictEqual(240 descriptor241 );242 });243 });244 /* eslint-disable @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-call */245 describe('bind function', () => {246 globalObj.func = function () {247 return this;248 };249 globalObj.func.testValue = 'test123';250 globalObj.func.setValue = function (value: string) {251 this.testValue = value;252 };253 interceptedObj.funcIntercept = function () {254 return this;255 };256 it('should not bind property function if non native function', () => {257 expect(globalObj.func()).toBe(globalObj);258 expect(interceptedObj.func()).toBe(interceptedObj);259 });260 it('should not bind function on interceptedObject if non native function', () => {261 expect(globalObj.funcIntercept()).toBe(globalObj);262 expect(interceptedObj.funcIntercept()).toBe(interceptedObj);263 });264 it('should bind property function if native', () => {265 // force interceptObject to bind the functions for the rest of the tests266 fakeToString(globalObj.func);267 fakeToString(globalObj.funcIntercept);268 expect(globalObj.func()).toBe(globalObj);269 expect(interceptedObj.func()).toBe(globalObj);270 });271 it('should bind function on interceptedObject if native', () => {272 expect(globalObj.funcIntercept()).toBe(globalObj);273 expect(interceptedObj.funcIntercept()).toBe(globalObj);274 });275 it('should bind property function with prop.call if native and binded this is interceptedObj', () => {276 expect(interceptedObj.func.call(interceptedObj)).toBe(globalObj);277 });278 it('should bind property function on interceptedObject with prop.call if native and binded this is interceptedObj', () => {279 expect(interceptedObj.funcIntercept.call(interceptedObj)).toBe(globalObj);280 });281 it('two binded functions should be equal', () => {282 expect(globalObj.func).toBe(globalObj.func);283 expect(interceptedObj.func).toBe(interceptedObj.func);284 expect(globalObj.funcIntercept).toBe(globalObj.funcIntercept);285 expect(interceptedObj.funcIntercept).toBe(interceptedObj.funcIntercept);286 });287 it('should work with func.call', () => {288 const thisObj = {289 some: 'property'290 };291 expect(globalObj.func.call(thisObj)).toBe(thisObj);292 expect(globalObj.funcIntercept.call(thisObj)).toBe(thisObj);293 expect(interceptedObj.func.call(thisObj)).toBe(thisObj);294 expect(interceptedObj.funcIntercept.call(thisObj)).toBe(thisObj);295 });296 it('should work with func.propFunc.call', () => {297 const thisObj = {298 some: 'property'299 };300 globalObj.funcIntercept.propFunc = function () {301 return this;302 };303 interceptedObj.func.propFunc = function () {304 return this;305 };306 interceptedObj.funcIntercept.testValue = '123';307 fakeToString(globalObj.func.propFunc);308 fakeToString(globalObj.funcIntercept.propFunc);309 expect(globalObj.func.propFunc.call(thisObj)).toBe(thisObj);310 expect(globalObj.funcIntercept.propFunc.call(thisObj)).toBe(thisObj);311 expect(interceptedObj.func.propFunc.call(thisObj)).toBe(thisObj);312 expect(interceptedObj.funcIntercept.propFunc.call(thisObj)).toBe(thisObj);313 });314 it('should return this when func.propFunc()', () => {315 expect(globalObj.func.propFunc()).toBe(globalObj.func);316 expect(globalObj.funcIntercept.propFunc()).toBe(globalObj.funcIntercept);317 expect(interceptedObj.func.propFunc()).toBe(globalObj.func);318 expect(interceptedObj.funcIntercept.propFunc()).toBe(globalObj.funcIntercept);319 });320 it('two binded function properties should be equal', () => {321 expect(globalObj.func.propFunc).toBe(globalObj.func.propFunc);322 expect(interceptedObj.func.propFunc).toBe(interceptedObj.func.propFunc);323 expect(globalObj.funcIntercept.propFunc).toBe(globalObj.funcIntercept.propFunc);324 expect(interceptedObj.funcIntercept.propFunc).toBe(interceptedObj.funcIntercept.propFunc);325 });326 it('should work with func.bind', () => {327 const thisObj = {328 some: 'property'329 };330 expect(globalObj.func.bind(thisObj)()).toStrictEqual(thisObj);331 expect(globalObj.funcIntercept.bind(thisObj)()).toStrictEqual(thisObj);332 expect(interceptedObj.func.bind(thisObj)()).toStrictEqual(thisObj);333 expect(interceptedObj.funcIntercept.bind(thisObj)()).toStrictEqual(thisObj);334 });335 it('should work with Function.prototype.call.call', () => {336 const thisObj = {337 some: 'otherproperty'338 };339 expect(Function.prototype.call.call(globalObj.func, thisObj)).toBe(thisObj);340 expect(Function.prototype.call.call(globalObj.funcIntercept, thisObj)).toBe(thisObj);341 expect(Function.prototype.call.call(interceptedObj.func, thisObj)).toBe(thisObj);342 expect(Function.prototype.call.call(interceptedObj.funcIntercept, thisObj)).toBe(thisObj);343 });344 it('should mirror function properties of function', () => {345 expect(globalObj.func.testValue).toEqual('test123');346 expect(interceptedObj.func.testValue).toEqual('test123');347 });348 it('should mirror function property changes', () => {349 globalObj.func.propChangeTestGlobal = 'change globalObj';350 interceptedObj.func.propChangeTestIntercept = 'change interceptedObj';351 expect(globalObj.func.propChangeTestGlobal).toEqual('change globalObj');352 expect(interceptedObj.func.propChangeTestGlobal).toEqual('change globalObj');353 expect(globalObj.func.propChangeTestIntercept).toEqual('change interceptedObj');354 expect(interceptedObj.func.propChangeTestIntercept).toEqual('change interceptedObj');355 });356 it('property should be called with "this" binded properly', () => {357 globalObj.func.setValue('set from globalObj');358 expect(globalObj.func.testValue).toEqual('set from globalObj');359 expect(interceptedObj.func.testValue).toEqual('set from globalObj');360 globalObj.func.setValue('set from interceptedObj');361 expect(globalObj.func.testValue).toEqual('set from interceptedObj');362 expect(interceptedObj.func.testValue).toEqual('set from interceptedObj');363 });364 it('should inherit with __proto__', () => {365 interceptedObj.funcProto = Object.create(interceptedObj.func);366 expect(globalObj.funcProto.testValue).toEqual('set from interceptedObj');367 expect(interceptedObj.funcProto.testValue).toEqual('set from interceptedObj');368 interceptedObj.func.testValue = 23;369 expect(globalObj.funcProto.testValue).toEqual(23);370 expect(interceptedObj.funcProto.testValue).toEqual(23);371 });372 });373 describe('__proto__ inheritance', () => {374 interceptedObj.protoParent = {375 parentValue: 123376 };377 interceptedObj.protoChild = Object.create(interceptedObj.protoParent);378 it('should inherit correctly', () => {379 expect(globalObj.protoChild.parentValue).toEqual(123);380 expect(interceptedObj.protoChild.parentValue).toEqual(123);381 });382 });383 describe('es5 classes', () => {384 globalObj.ES5ClassGlobal = function (inputNumber: number) {385 this.currentNumber = inputNumber;386 };387 globalObj.ES5ClassGlobal.prototype = {388 add(addValue: number) {389 return this.currentNumber + addValue;390 }391 };392 interceptedObj.ES5ClassIntercept = function (inputNumber: number) {393 this.currentNumber = inputNumber;394 };395 interceptedObj.ES5ClassIntercept.prototype = {396 add(addValue: number) {397 return this.currentNumber + addValue;398 }399 };400 it('should run prototype method correctly using es5 class created through globalObj', () => {401 expect(new globalObj.ES5ClassGlobal(3).add(3)).toEqual(6);402 expect(new interceptedObj.ES5ClassGlobal(4).add(3)).toEqual(7);403 });404 it('should run prototype method correctly using es5 class created through interceptedObj', () => {405 expect(new globalObj.ES5ClassIntercept(5).add(3)).toEqual(8);406 expect(new interceptedObj.ES5ClassIntercept(6).add(3)).toEqual(9);407 });408 });409 describe('Object.keys', () => {410 it('should be same for both', () => {411 expect(Object.keys(globalObj)).toEqual(Object.keys(interceptedObj));412 });413 });414 /* eslint-disable @typescript-eslint/no-unsafe-member-access */415 });...

Full Screen

Full Screen

decoratorsTest.ts

Source:decoratorsTest.ts Github

copy

Full Screen

1import * as expect from "expect";2import * as simple from "simple-mock";3import { timedMatrixClientFunctionCall, timedIntentFunctionCall, Metrics } from "../../src";4class InterceptedClass {5 constructor(private metrics: Metrics, private interceptedFn: (i: number) => number) {6 this.client = { userId: 5678 };7 }8 @timedMatrixClientFunctionCall()9 async matrixClientIntercepted(i: number): Promise<number> {10 return this.interceptedFn(i);11 }12 @timedIntentFunctionCall()13 async intentIntercepted(i: number) : Promise<number> {14 return this.interceptedFn(i);15 }16}17// Not a fan of this but the promise with metrics chained isn't returned, just the original before the metrics were chained18// I think this is deliberate so that metrics slow down any promises that later get chained19// If we could return the promise with metrics chained this can go away.20const waitingPromise = () => new Promise((resolve) => setTimeout(resolve, 10));21describe('decorators', () => {22 describe('timedMatrixClientFunctionCall', () => {23 it('should call the intercepted method with provided args', async () => {24 const amount = 1234;25 const interceptedFn = simple.stub().callFn((i: number) => {26 expect(i).toBe(amount);27 return -1;28 });29 const interceptedClass = new InterceptedClass(new Metrics(), interceptedFn);30 await interceptedClass.matrixClientIntercepted(amount);31 expect(interceptedFn.callCount).toBe(1);32 });33 it('should return the result of the intercepted method', async () => {34 const amount = 1234;35 const interceptedClass = new InterceptedClass(new Metrics(), (i) => amount);36 const result = await interceptedClass.matrixClientIntercepted(amount * 2);37 expect(result).toBe(amount);38 });39 it('should expose errors from the intercepted method', async () => {40 const reason = "Bad things";41 const interceptedClass = new InterceptedClass(new Metrics(), () => {42 throw new Error(reason);43 });44 await expect(interceptedClass.matrixClientIntercepted(1234)).rejects.toThrow(reason);45 });46 it('should call start on metrics with function name before calling intercepted method', async () => {47 const metrics = new Metrics();48 simple.mock(metrics, "start");49 const interceptedFn = simple.stub().callFn((i: number) => {50 expect(metrics.start.callCount).toBe(1);51 expect(metrics.start.lastCall.args[0]).toBe("matrix_client_function_call");52 expect(metrics.start.lastCall.args[1]).toHaveProperty("functionName", "matrixClientIntercepted");53 return -1;54 });55 const interceptedClass = new InterceptedClass(metrics, interceptedFn);56 await interceptedClass.matrixClientIntercepted(1234);57 });58 it('should call end on metrics with function name after calling intercepted method', async () => {59 const metrics = new Metrics();60 simple.mock(metrics, "end");61 const interceptedFn = simple.stub().callFn((i: number) => {62 expect(metrics.end.callCount).toBe(0);63 return -1;64 });65 const interceptedClass = new InterceptedClass(metrics, interceptedFn);66 await interceptedClass.matrixClientIntercepted(1234).then(waitingPromise);67 expect(metrics.end.callCount).toBe(1);68 expect(metrics.end.lastCall.args[0]).toBe("matrix_client_function_call");69 expect(metrics.end.lastCall.args[1]).toHaveProperty("functionName", "matrixClientIntercepted");70 });71 it('should increment the successful counter on returning a result', async () => {72 const metrics = new Metrics();73 simple.mock(metrics, "increment");74 const interceptedFn = simple.stub().callFn((i: number) => {75 expect(metrics.increment.callCount).toBe(0);76 return -1;77 });78 const interceptedClass = new InterceptedClass(metrics, interceptedFn);79 await interceptedClass.matrixClientIntercepted(1234).then(waitingPromise);80 expect(metrics.increment.callCount).toBe(1);81 expect(metrics.increment.lastCall.args[0]).toBe("matrix_client_successful_function_call");82 expect(metrics.increment.lastCall.args[1]).toHaveProperty("functionName", "matrixClientIntercepted");83 });84 it('should increment the failure counter on throwing', async () => {85 const metrics = new Metrics();86 simple.mock(metrics, "increment");87 const interceptedFn = simple.stub().callFn((i: number) => {88 expect(metrics.increment.callCount).toBe(0);89 throw new Error("Bad things");90 });91 const interceptedClass = new InterceptedClass(metrics, interceptedFn);92 await interceptedClass.matrixClientIntercepted(1234).catch(waitingPromise);93 expect(metrics.increment.callCount).toBe(1);94 expect(metrics.increment.lastCall.args[0]).toBe("matrix_client_failed_function_call");95 expect(metrics.increment.lastCall.args[1]).toHaveProperty("functionName", "matrixClientIntercepted");96 });97 });98 describe('timedIntentFunctionCall', () => {99 it('should call the intercepted method with provided args', async () => {100 const amount = 1234;101 const interceptedFn = simple.stub().callFn((i: number) => {102 expect(i).toBe(amount);103 return -1;104 });105 const interceptedClass = new InterceptedClass(new Metrics(), interceptedFn);106 await interceptedClass.intentIntercepted(amount);107 expect(interceptedFn.callCount).toBe(1);108 });109 it('should return the result of the intercepted method', async () => {110 const amount = 1234;111 const interceptedClass = new InterceptedClass(new Metrics(), (i) => amount);112 const result = await interceptedClass.intentIntercepted(amount * 2);113 expect(result).toBe(amount);114 });115 it('should expose errors from the intercepted method', async () => {116 const reason = "Bad things";117 const interceptedClass = new InterceptedClass(new Metrics(), () => {118 throw new Error(reason);119 });120 await expect(interceptedClass.intentIntercepted(1234)).rejects.toThrow(reason);121 });122 it('should call start on metrics with function name before calling intercepted method', async () => {123 const metrics = new Metrics();124 simple.mock(metrics, "start");125 const interceptedFn = simple.stub().callFn((i: number) => {126 expect(metrics.start.callCount).toBe(1);127 expect(metrics.start.lastCall.args[0]).toBe("intent_function_call");128 expect(metrics.start.lastCall.args[1]).toHaveProperty("functionName", "intentIntercepted");129 return -1;130 });131 const interceptedClass = new InterceptedClass(metrics, interceptedFn);132 await interceptedClass.intentIntercepted(1234);133 });134 it('should call end on metrics with function name after calling intercepted method', async () => {135 const metrics = new Metrics();136 simple.mock(metrics, "end");137 const interceptedFn = simple.stub().callFn((i: number) => {138 expect(metrics.end.callCount).toBe(0);139 return -1;140 });141 const interceptedClass = new InterceptedClass(metrics, interceptedFn);142 await interceptedClass.intentIntercepted(1234).then(waitingPromise);143 expect(metrics.end.callCount).toBe(1);144 expect(metrics.end.lastCall.args[0]).toBe("intent_function_call");145 expect(metrics.end.lastCall.args[1]).toHaveProperty("functionName", "intentIntercepted");146 });147 it('should increment the successful counter on returning a result', async () => {148 const metrics = new Metrics();149 simple.mock(metrics, "increment");150 const interceptedFn = simple.stub().callFn((i: number) => {151 expect(metrics.increment.callCount).toBe(0);152 return -1;153 });154 const interceptedClass = new InterceptedClass(metrics, interceptedFn);155 await interceptedClass.intentIntercepted(1234).then(waitingPromise);156 expect(metrics.increment.callCount).toBe(1);157 expect(metrics.increment.lastCall.args[0]).toBe("intent_successful_function_call");158 expect(metrics.increment.lastCall.args[1]).toHaveProperty("functionName", "intentIntercepted");159 });160 it('should increment the failure counter on throwing', async () => {161 const metrics = new Metrics();162 simple.mock(metrics, "increment");163 const interceptedFn = simple.stub().callFn((i: number) => {164 expect(metrics.increment.callCount).toBe(0);165 throw new Error("Bad things");166 });167 const interceptedClass = new InterceptedClass(metrics, interceptedFn);168 await interceptedClass.intentIntercepted(1234).catch(waitingPromise);169 expect(metrics.increment.callCount).toBe(1);170 expect(metrics.increment.lastCall.args[0]).toBe("intent_failed_function_call");171 expect(metrics.increment.lastCall.args[1]).toHaveProperty("functionName", "intentIntercepted");172 });173 });...

Full Screen

Full Screen

fetch_wrapper.ts

Source:fetch_wrapper.ts Github

copy

Full Screen

1import * as utils from "./utils.ts";2import {3 ExtendedRequest,4 ExtendedRequestInit,5 Interceptors,6} from "./extended_request_init.ts";7/**8 * Transforms data and adds corresponding headers if possible.9 */10function transformData(11 data:12 | string13 | Record<string, unknown>14 | ArrayBuffer15 | Blob16 | ArrayBufferView17 | FormData18 | URLSearchParams19 | ReadableStream<Uint8Array>20 | null21 | undefined,22 headers: Headers,23 init?: RequestInit | ExtendedRequestInit,24):25 | string26 | ArrayBuffer27 | Blob28 | ArrayBufferView29 | FormData30 | URLSearchParams31 | ReadableStream<Uint8Array>32 | null33 | undefined {34 if (35 utils.isFormData(data) ||36 utils.isArrayBuffer(data) ||37 utils.isBuffer(data) ||38 utils.isStream(data) ||39 utils.isFile(data) ||40 utils.isBlob(data)41 ) {42 return data;43 }44 if (utils.isArrayBufferView(data)) {45 return data.buffer;46 }47 if (utils.isURLSearchParams(data)) {48 headers.set(49 "Content-Type",50 "application/x-www-form-urlencoded;charset=utf-8",51 );52 return data.toString();53 }54 if (utils.isObject(data)) {55 headers.set("Content-Type", "application/json;charset=utf-8");56 if (init && !init.method) {57 init.method = "POST";58 }59 return JSON.stringify(data);60 }61 // the default header if type undefined62 headers.set("Content-Type", "application/x-www-form-urlencoded");63 return data;64}65export type WrapFetchOptions = {66 /** your own fetch function. defaults to global fetch. */67 fetch?: typeof fetch;68 /** user agent header string */69 userAgent?: string;70 /** if set, all requests will timeout after this amount of milliseconds passed */71 timeout?: number;72 /** if set, will be used as default headers. new added headers will be added on top of these. */73 headers?: Headers;74 /** if set, will be prepended to the target url using URL api. */75 baseURL?: string | URL;76 /** interceptors can be used for validating request and response and throwing errors */77 interceptors?: Interceptors;78};79export function wrapFetch(options?: WrapFetchOptions) {80 const {81 fetch = globalThis.fetch,82 userAgent,83 interceptors,84 timeout = 99999999,85 headers,86 baseURL,87 } = options || {};88 return async function wrappedFetch(89 input: string | Request | URL,90 init?: ExtendedRequestInit | RequestInit | undefined,91 ) {92 // let fetch handle the error93 if (!input) {94 return await fetch(input);95 }96 const interceptedInit = init || {};97 if (!(interceptedInit.headers instanceof Headers)) {98 interceptedInit.headers = new Headers(interceptedInit.headers || {});99 }100 {101 const baseHeaders = new Headers(headers);102 for (const header of interceptedInit.headers) {103 baseHeaders.set(header[0], header[1]);104 }105 interceptedInit.headers = baseHeaders;106 }107 // Normalize input to URL. when reading the specs (https://fetch.spec.whatwg.org/#request and https://fetch.spec.whatwg.org/#fetch-method),108 // I didn't see anything mentioned about fetch using anything from an input that is instance of Request except It's URL.109 // So it is safe to discard the Request object and use It's url only.110 // Normalizing the url simplifies any feature we want to add later.111 {112 if (typeof input !== "string") {113 if (input instanceof Request) {114 input = input.url;115 } else {116 input = input.toString();117 }118 }119 // URL doesn't support relative urls120 if (input.includes("://")) {121 input = new URL(input);122 } else {123 if (baseURL) {124 input = new URL(input, baseURL);125 } else {126 try {127 input = new URL(input, location.href);128 } catch {129 throw new Error(130 "Cannot parse the input url. Either provide `--location` parameter to Deno, or use complete url, or use baseURL when wrapping fetch.",131 );132 }133 }134 }135 }136 // add url to interceptedInit137 (interceptedInit as ExtendedRequest).url = input;138 // setup a default accept139 if (!interceptedInit.headers.get("Accept")) {140 interceptedInit.headers.set(141 "Accept",142 "application/json, text/plain, */*",143 );144 }145 // setup user agent if set146 if (userAgent) {147 interceptedInit.headers.set("User-Agent", userAgent);148 }149 if ("form" in interceptedInit && interceptedInit.form) {150 interceptedInit.body = "";151 for (const key of Object.keys(interceptedInit.form)) {152 if (typeof interceptedInit.form[key] === "string") {153 interceptedInit.body += `${encodeURIComponent(key)}=${154 encodeURIComponent(interceptedInit.form[key] as string)155 }&`;156 } else {157 for (const str of interceptedInit.form[key]) {158 interceptedInit.body += `${encodeURIComponent(key)}[]=${159 encodeURIComponent(str as string)160 }&`;161 }162 }163 }164 // remove ending &165 if (interceptedInit.body) {166 interceptedInit.body = interceptedInit.body.substring(167 0,168 interceptedInit.body.length - 1,169 );170 }171 if (!interceptedInit.method) {172 interceptedInit.method = "POST";173 }174 }175 if ("formData" in interceptedInit && interceptedInit.formData) {176 interceptedInit.body = new FormData();177 for (const key of Object.keys(interceptedInit.formData)) {178 if (typeof interceptedInit.formData[key] === "string") {179 interceptedInit.body.append(180 key,181 interceptedInit.formData[key] as string,182 );183 } else {184 for (const str of interceptedInit.formData[key]) {185 interceptedInit.body.append(key, str);186 }187 }188 }189 if (!interceptedInit.method) {190 interceptedInit.method = "POST";191 }192 }193 if ("qs" in interceptedInit && interceptedInit.qs) {194 // remove undefined values195 const filteredQs = Object.entries(interceptedInit.qs).filter(196 ([_, qv]) => {197 if (qv !== undefined) return true;198 return false;199 },200 ) as [string, string][];201 const searchParams = new URLSearchParams(filteredQs);202 for (const [spKey, spValue] of searchParams.entries()) {203 if (spValue !== undefined) {204 input.searchParams.set(spKey, spValue);205 }206 }207 }208 if (interceptedInit.body) {209 interceptedInit.body = transformData(210 interceptedInit.body,211 interceptedInit.headers,212 interceptedInit,213 );214 }215 let timeoutId: undefined | number;216 if (("timeout" in interceptedInit && interceptedInit.timeout) || timeout) {217 const abortController = new AbortController();218 timeoutId = setTimeout(219 () => abortController.abort(new Error("Timeout has been exceeded")),220 (interceptedInit as ExtendedRequestInit).timeout || timeout,221 );222 interceptedInit.signal = abortController.signal;223 }224 if (typeof interceptors?.request === "function") {225 await interceptors.request(interceptedInit as ExtendedRequest);226 }227 if (228 "interceptors" in interceptedInit &&229 typeof interceptedInit.interceptors?.request === "function"230 ) {231 await interceptedInit.interceptors.request(232 interceptedInit as ExtendedRequest,233 );234 }235 const response = await fetch(input, interceptedInit as RequestInit);236 clearTimeout(timeoutId);237 if (typeof interceptors?.response === "function") {238 await interceptors.response(interceptedInit as ExtendedRequest, response);239 }240 if (241 "interceptors" in interceptedInit &&242 typeof interceptedInit.interceptors?.response === "function"243 ) {244 await interceptedInit.interceptors.response(245 interceptedInit as ExtendedRequest,246 response,247 );248 }249 return response;250 };...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1var wpt = require('wpt');2 if (err) {3 console.log('Error: ' + err);4 } else {5 console.log('Test Results: ' + data);6 }7});8* **Sandeep Kumar** - [sandeepkumar](

Full Screen

Using AI Code Generation

copy

Full Screen

1var wpt = require('webpagetest');2wpt = wpt('API_KEY');3wpt.intercept = function (options, callback) {4 console.log('intercepted');5 var req = http.request(options, function (res) {6 console.log('intercepted');7 res.setEncoding('utf8');8 res.on('data', function (chunk) {9 console.log('intercepted');10 callback(null, chunk);11 });12 });13 req.on('error', function (err) {14 console.log('intercepted');15 callback(err);16 });17 req.end();18};19 console.log('intercepted');20 if (err) return console.error(err);21 console.log(data);22});23public boolean isElementPresent(By by) {24 try {25 driver.findElement(by);26 return true;27 } catch (NoSuchElementException e) {28 return false;29 }30}31if (fs.existsSync('/path/to/file')) {32}33if (fs.existsSync('/path/to/file')) {34}35var cookie = driver.manage().getCookieNamed('someCookie

Full Screen

Using AI Code Generation

copy

Full Screen

1var wpt = require('wpt');2});3var wpt = require('wpt');4});5var wpt = require('wpt');6});7var wpt = require('wpt');8});9var wpt = require('wpt');10});11var wpt = require('wpt');12});13var wpt = require('wpt');

Full Screen

Using AI Code Generation

copy

Full Screen

1const wpt = require('wpt');2const wptHook = require('wpt-hook');3const wptHooked = wptHook(hookedWPT);4const wpt = require('wpt');5const wptHook = require('wpt-hook');6const wptHooked = wptHook(hookedWPT);7const wpt = require('wpt');8const wptHook = require('wpt-hook');9const wptHooked = wptHook(hookedWPT);10const wpt = require('wpt');11const wptHook = require('wpt-hook');12const wptHooked = wptHook(hookedWPT);13const wpt = require('wpt');14const wptHook = require('wpt-hook');15const wptHooked = wptHook(hookedWPT);16const wpt = require('wpt');17const wptHook = require('wpt-hook');18const wptHooked = wptHook(hookedWPT);19const wpt = require('wpt');20const wptHook = require('wpt-hook');21const wptHooked = wptHook(hookedWPT);22const wpt = require('wpt');23const wptHook = require('wpt-hook');24const wptHooked = wptHook(hookedWPT);25const wpt = require('wpt');26const wptHook = require('wpt-hook');27const wptHooked = wptHook(hookedWPT);28const wpt = require('wpt');29const wptHook = require('wpt-hook');30const wptHooked = wptHook(hookedWPT);31const wpt = require('wpt');32const wptHook = require('wpt-hook');33const wptHooked = wptHook(hookedWPT);

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run wpt automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful