How to use initiateFetch method in wpt

Best JavaScript code snippet using wpt

resource-timing-level1.js

Source:resource-timing-level1.js Github

copy

Full Screen

...23 // Insert an empty IFrame.24 var frame = document.createElement("iframe");25 // Wait for the IFrame to load and ensure there is no resource entry for it on the timeline.26 //27 // We use the 'createOnloadCallbackFn()' helper which is normally invoked by 'initiateFetch()'28 // to avoid setting the IFrame's src. It registers a test step for us, finds our entry on the29 // resource timeline, and wraps our callback function to automatically vet invariants.30 frame.onload = createOnloadCallbackFn(test, frame, "about:blank",31 function (initiator, entry) {32 assert_equals(entry, undefined, "Inserting an IFrame with a src of 'about:blank' must not add an entry to the timeline.");33 assertInvariants(34 test,35 function () {36 test.done();37 });38 });39 document.body.appendChild(frame);40 // Paranoid check that the new IFrame has loaded about:blank.41 assert_equals(42 frame.contentWindow.location.href,43 "about:blank",44 "'Src' of new <iframe> must be 'about:blank'.");45 }46 },47 ];48 // Create cached/uncached tests from the following array of templates. For each template entry,49 // we add two identical test cases to 'testCases'. The first case initiates a fetch to populate the50 // cache. The second request initiates a fetch with the same URL to cover the case where we hit51 // the cache (if the caching policy permits caching).52 [53 { initiator: "iframe", response: "(done)", mime: mimeHtml },54 { initiator: "xmlhttprequest", response: "(done)", mime: mimeText },55 // Multiple browsers seem to cheat a bit and race onLoad of images. Microsoft https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/237918756 // { initiator: "img", response: greenPng, mime: mimePng },57 { initiator: "script", response: '"";', mime: mimeScript },58 { initiator: "link", response: ".unused{}", mime: mimeCss },59 ]60 .forEach(function (template) {61 testCases.push({62 description: "'" + template.initiator + " (Populate cache): The initial request populates the cache (if appropriate).",63 test: function (test) {64 initiateFetch(65 test,66 template.initiator,67 getSyntheticUrl(68 "mime:" + encodeURIComponent(template.mime)69 + "&send:" + encodeURIComponent(template.response),70 /* allowCaching = */ true),71 function (initiator, entry) {72 test.done();73 });74 }75 });76 testCases.push({77 description: "'" + template.initiator + " (Potentially Cached): Immediately fetch the same URL, exercising the cache hit path (if any).",78 test: function (test) {79 initiateFetch(80 test,81 template.initiator,82 getSyntheticUrl(83 "mime:" + encodeURIComponent(template.mime)84 + "&send:" + encodeURIComponent(template.response),85 /* allowCaching = */ true),86 function (initiator, entry) {87 test.done();88 });89 }90 });91 });92 // Create responseStart/responseEnd tests from the following array of templates. In this test, the server delays before93 // responding with responsePart1, then delays again before completing with responsePart2. The test looks for the expected94 // pauses before responseStart and responseEnd.95 [96 { initiator: "iframe", responsePart1: serverStepDelay + "ms;", responsePart2: (serverStepDelay * 2) + "ms;(done)", mime: mimeHtml },97 { initiator: "xmlhttprequest", responsePart1: serverStepDelay + "ms;", responsePart2: (serverStepDelay * 2) + "ms;(done)", mime: mimeText },98 // Multiple browsers seem to cheat a bit and race img.onLoad and setting responseEnd. Microsoft https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/237918799 // { initiator: "img", responsePart1: greenPng.substring(0, greenPng.length / 2), responsePart2: "0x" + greenPng.substring(greenPng.length / 2, greenPng.length), mime: mimePng },100 { initiator: "script", responsePart1: '"', responsePart2: '";', mime: mimeScript },101 { initiator: "link", responsePart1: ".unused{", responsePart2: "}", mime: mimeCss },102 ]103 .forEach(function (template) {104 testCases.push({105 description: "'" + template.initiator + ": " + serverStepDelay + "ms delay before 'responseStart', another " + serverStepDelay + "ms delay before 'responseEnd'.",106 test: function (test) {107 initiateFetch(108 test,109 template.initiator,110 getSyntheticUrl(serverStepDelay + "ms" // Wait, then echo back responsePart1111 + "&mime:" + encodeURIComponent(template.mime)112 + "&send:" + encodeURIComponent(template.responsePart1)113 + "&" + serverStepDelay + "ms" // Wait, then echo back responsePart2114 + "&send:" + encodeURIComponent(template.responsePart2)),115 function (initiator, entry) {116 // Per https://w3c.github.io/resource-timing/#performanceresourcetiming:117 // If no redirects (or equivalent) occur, this redirectStart/End must return zero.118 assert_equals(entry.redirectStart, 0, "When no redirect occurs, redirectStart must be 0.");119 assert_equals(entry.redirectEnd, 0, "When no redirect occurs, redirectEnd must be 0.");120 // Server creates a gap between 'requestStart' and 'responseStart'.121 assert_greater_than_equal(122 entry.responseStart,123 entry.requestStart + serverStepDelay,124 "'responseStart' must be " + serverStepDelay + "ms later than 'requestStart'.");125 // Server creates a gap between 'responseStart' and 'responseEnd'.126 assert_greater_than_equal(127 entry.responseEnd,128 entry.responseStart + serverStepDelay,129 "'responseEnd' must be " + serverStepDelay + "ms later than 'responseStart'.");130 test.done();131 });132 }133 });134 });135 // Create redirectEnd/responseStart tests from the following array of templates. In this test, the server delays before136 // redirecting to a new synthetic response, then delays again before responding with 'response'. The test looks for the137 // expected pauses before redirectEnd and responseStart.138 [139 { initiator: "iframe", response: serverStepDelay + "ms;redirect;" + (serverStepDelay * 2) + "ms;(done)", mime: mimeHtml },140 { initiator: "xmlhttprequest", response: serverStepDelay + "ms;redirect;" + (serverStepDelay * 2) + "ms;(done)", mime: mimeText },141 // Multiple browsers seem to cheat a bit and race img.onLoad and setting responseEnd. Microsoft https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/2379187142 // { initiator: "img", response: greenPng, mime: mimePng },143 { initiator: "script", response: '"";', mime: mimeScript },144 { initiator: "link", response: ".unused{}", mime: mimeCss },145 ]146 .forEach(function (template) {147 testCases.push({148 description: "'" + template.initiator + " (Redirected): " + serverStepDelay + "ms delay before 'redirectEnd', another " + serverStepDelay + "ms delay before 'responseStart'.",149 test: function (test) {150 initiateFetch(151 test,152 template.initiator,153 getSyntheticUrl(serverStepDelay + "ms" // Wait, then redirect to a second page that waits154 + "&redirect:" // before echoing back the response.155 + encodeURIComponent(156 getSyntheticUrl(serverStepDelay + "ms"157 + "&mime:" + encodeURIComponent(template.mime)158 + "&send:" + encodeURIComponent(template.response)))),159 function (initiator, entry) {160 // Per https://w3c.github.io/resource-timing/#performanceresourcetiming:161 // "[If redirected, startTime] MUST return the same value as redirectStart.162 assert_equals(entry.startTime, entry.redirectStart, "startTime must be equal to redirectStart.");163 // Server creates a gap between 'redirectStart' and 'redirectEnd'.164 assert_greater_than_equal(165 entry.redirectEnd,166 entry.redirectStart + serverStepDelay,167 "'redirectEnd' must be " + serverStepDelay + "ms later than 'redirectStart'.");168 // Server creates a gap between 'requestStart' and 'responseStart'.169 assert_greater_than_equal(170 entry.responseStart,171 entry.requestStart + serverStepDelay,172 "'responseStart' must be " + serverStepDelay + "ms later than 'requestStart'.");173 test.done();174 });175 }176 });177 });178 // Ensure that responseStart only measures the time up to the first few179 // bytes of the header response. This is tested by writing an HTTP 1.1180 // status line, followed by a flush, then a pause before the end of the181 // headers. The test makes sure that responseStart is not delayed by182 // this pause.183 [184 { initiator: "iframe", response: "(done)", mime: mimeHtml },185 { initiator: "xmlhttprequest", response: "(done)", mime: mimeText },186 { initiator: "script", response: '"";', mime: mimeScript },187 { initiator: "link", response: ".unused{}", mime: mimeCss },188 ]189 .forEach(function (template) {190 testCases.push({191 description: "'" + template.initiator + " " + serverStepDelay + "ms delay in headers does not affect responseStart'",192 test: function (test) {193 initiateFetch(194 test,195 template.initiator,196 getSyntheticUrl("status:200"197 + "&flush"198 + "&" + serverStepDelay + "ms"199 + "&mime:" + template.mime200 + "&send:" + encodeURIComponent(template.response)),201 function (initiator, entry) {202 // Test that the delay between 'responseStart' and203 // 'responseEnd' includes the delay, which implies204 // that 'responseStart' was measured at the time of205 // status line receipt.206 assert_greater_than_equal(207 entry.responseEnd,208 entry.responseStart + serverStepDelay,209 "Delay after HTTP/1.1 status should not affect 'responseStart'.");210 test.done();211 });212 }213 });214 });215 // Test that responseStart uses the timing of 1XX responses by216 // synthesizing a delay between a 100 and 200 status, and verifying that217 // this delay is included before responseEnd. If the delay is not218 // included, this implies that the 200 status line was (incorrectly) used219 // for responseStart timing, despite the 100 response arriving earlier.220 //221 // Source: "In the case where more than one response is available for a222 // request, due to an Informational 1xx response, the reported223 // responseStart value is that of the first response to the last224 // request."225 [226 { initiator: "iframe", response: "(done)", mime: mimeHtml },227 { initiator: "xmlhttprequest", response: "(done)", mime: mimeText },228 { initiator: "script", response: '"";', mime: mimeScript },229 { initiator: "link", response: ".unused{}", mime: mimeCss },230 ]231 .forEach(function (template) {232 testCases.push({233 description: "'" + template.initiator + " responseStart uses 1XX (first) response timings'",234 test: function (test) {235 initiateFetch(236 test,237 template.initiator,238 getSyntheticUrl("status:100"239 + "&flush"240 + "&" + serverStepDelay + "ms"241 + "&status:200"242 + "&mime:" + template.mime243 + "&send:" + encodeURIComponent(template.response)),244 function (initiator, entry) {245 assert_greater_than_equal(246 entry.responseEnd,247 entry.responseStart + serverStepDelay,248 "HTTP/1.1 1XX (first) response should determine 'responseStart' timing.");249 test.done();250 });251 }252 });253 });254 // Function to run the next case in the queue.255 var currentTestIndex = -1;256 function runNextCase() {257 var testCase = testCases[++currentTestIndex];258 if (testCase !== undefined) {259 async_test(testCase.test, testCase.description);260 }261 }262 // When a test completes, run the next case in the queue.263 add_result_callback(runNextCase);264 // Start the first test.265 runNextCase();266 /** Iterates through all resource entries on the timeline, vetting all invariants. */267 function assertInvariants(test, done) {268 // Multiple browsers seem to cheat a bit and race img.onLoad and setting responseEnd. Microsoft https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/2379187269 // Yield for 100ms to workaround a suspected race where window.onload fires before270 // script visible side-effects from the wininet/urlmon thread have finished.271 test.step_timeout(272 test.step_func(273 function () {274 performance275 .getEntriesByType("resource")276 .forEach(277 function (entry, index, entries) {278 assertResourceEntryInvariants(entry);279 });280 done();281 }),282 100);283 }284 /** Assets the invariants for a resource timeline entry. */285 function assertResourceEntryInvariants(actual) {286 // Example from http://w3c.github.io/resource-timing/#resources-included:287 // "If an HTML IFRAME element is added via markup without specifying a src attribute,288 // the user agent may load the about:blank document for the IFRAME. If at a later time289 // the src attribute is changed dynamically via script, the user agent may fetch the new290 // URL resource for the IFRAME. In this case, only the fetch of the new URL would be291 // included as a PerformanceResourceTiming object in the Performance Timeline."292 assert_not_equals(293 actual.name,294 "about:blank",295 "Fetch for 'about:blank' must not appear in timeline.");296 assert_not_equals(actual.startTime, 0, "startTime");297 // Per https://w3c.github.io/resource-timing/#performanceresourcetiming:298 // "[If redirected, startTime] MUST return the same value as redirectStart. Otherwise,299 // [startTime] MUST return the same value as fetchStart."300 assert_in_array(actual.startTime, [actual.redirectStart, actual.fetchStart],301 "startTime must be equal to redirectStart or fetchStart.");302 // redirectStart <= redirectEnd <= fetchStart <= domainLookupStart <= domainLookupEnd <= connectStart303 assert_less_than_equal(actual.redirectStart, actual.redirectEnd, "redirectStart <= redirectEnd");304 assert_less_than_equal(actual.redirectEnd, actual.fetchStart, "redirectEnd <= fetchStart");305 assert_less_than_equal(actual.fetchStart, actual.domainLookupStart, "fetchStart <= domainLookupStart");306 assert_less_than_equal(actual.domainLookupStart, actual.domainLookupEnd, "domainLookupStart <= domainLookupEnd");307 assert_less_than_equal(actual.domainLookupEnd, actual.connectStart, "domainLookupEnd <= connectStart");308 // Per https://w3c.github.io/resource-timing/#performanceresourcetiming:309 // "This attribute is optional. User agents that don't have this attribute available MUST set it310 // as undefined. [...] If the secureConnectionStart attribute is available but HTTPS is not used,311 // this attribute MUST return zero."312 assert_true(actual.secureConnectionStart == undefined ||313 actual.secureConnectionStart == 0 ||314 actual.secureConnectionStart >= actual.connectEnd, "secureConnectionStart time");315 // connectStart <= connectEnd <= requestStart <= responseStart <= responseEnd316 assert_less_than_equal(actual.connectStart, actual.connectEnd, "connectStart <= connectEnd");317 assert_less_than_equal(actual.connectEnd, actual.requestStart, "connectEnd <= requestStart");318 assert_less_than_equal(actual.requestStart, actual.responseStart, "requestStart <= responseStart");319 assert_less_than_equal(actual.responseStart, actual.responseEnd, "responseStart <= responseEnd");320 }321 /** Helper function to resolve a relative URL */322 function canonicalize(url) {323 var div = document.createElement('div');324 div.innerHTML = "<a></a>";325 div.firstChild.href = url;326 div.innerHTML = div.innerHTML;327 return div.firstChild.href;328 }329 /** Generates a unique string, used by getSyntheticUrl() to avoid hitting the cache. */330 function createUniqueQueryArgument() {331 var result =332 "ignored_"333 + Date.now()334 + "-"335 + ((Math.random() * 0xFFFFFFFF) >>> 0)336 + "-"337 + syntheticRequestCount;338 return result;339 }340 /** Count of the calls to getSyntheticUrl(). Used by createUniqueQueryArgument() to generate unique strings. */341 var syntheticRequestCount = 0;342 /** Return a URL to a server that will synthesize an HTTP response using the given343 commands. (See SyntheticResponse.aspx). */344 function getSyntheticUrl(commands, allowCache) {345 syntheticRequestCount++;346 var url =347 canonicalize("./SyntheticResponse.py") // ASP.NET page that will synthesize the response.348 + "?" + commands; // Commands that will be used.349 if (allowCache !== true) { // If caching is disallowed, append a unique argument350 url += "&" + createUniqueQueryArgument(); // to the URL's query string.351 }352 return url;353 }354 /** Given an 'initiatorType' (e.g., "img") , it triggers the appropriate type of fetch for the specified355 url and invokes 'onloadCallback' when the fetch completes. If the fetch caused an entry to be created356 on the resource timeline, the entry is passed to the callback. */357 function initiateFetch(test, initiatorType, url, onloadCallback) {358 assertInvariants(359 test,360 function () {361 log("--- Begin: " + url);362 switch (initiatorType) {363 case "script":364 case "img":365 case "iframe": {366 var element = document.createElement(initiatorType);367 document.body.appendChild(element);368 element.onload = createOnloadCallbackFn(test, element, url, onloadCallback);369 element.src = url;370 break;371 }...

Full Screen

Full Screen

useFetch.js

Source:useFetch.js Github

copy

Full Screen

...8}9export default function useFetch(fetchURL, fetchOptions = {}) {10 const [request, setRequest] = useState(null);11 12 async function initiateFetch() {13 setRequest({error:null, data:null})14 try {15 const finalFetchOptions = {16 ...DEFAULT_FETCH_OPTIONS,17 ...fetchOptions,18 headers : {19 ...DEFAULT_FETCH_OPTIONS.headers,20 ...fetchOptions.headers21 },22 }23 const response = await fetch(fetchURL, finalFetchOptions)24 const responseBody = await response.json()25 if (response.ok)26 setRequest({error:null, data:responseBody})...

Full Screen

Full Screen

cms.actions.test.ts

Source:cms.actions.test.ts Github

copy

Full Screen

...10 slug: "foo",11 });12 });13 });14 describe("initiateFetch()", () => {15 test("initiates an API fetch", () => {16 const slug = "foo";17 // @ts-expect-error ts-migrate(2345) FIXME: Argument of type '{ slug: string; }' is not assign... Remove this comment to see the full error message18 expect(initiateFetch({ slug })).toMatchObject({19 type: fetchTypes.FETCH,20 name: `${types.FETCH_PAGE_BY_SLUG}-${slug}`,21 });22 });23 test("fires a completed action when fetch finished", () => {24 const slug = "foo";25 // @ts-expect-error ts-migrate(2345) FIXME: Argument of type '{ slug: string; }' is not assign... Remove this comment to see the full error message26 expect(initiateFetch({ slug })).toMatchObject({27 postFetch: `${types.FETCH_PAGE_BY_SLUG_COMPLETE}-${slug}`,28 });29 });30 test("passes the fetcher function to the action", () => {31 const slug = "foo";32 // @ts-expect-error ts-migrate(2345) FIXME: Argument of type '{ slug: string; }' is not assign... Remove this comment to see the full error message33 const action = initiateFetch({ slug });34 expect(typeof action.asyncCall).toBe("function");35 });36 test("passes the right parameters to the fetcher function", () => {37 const slug = "foo";38 const hash = "123";39 const lang = "en";40 const action = initiateFetch({ slug, hash, lang });41 expect(action.asyncCallData).toEqual({ slug, hash, lang });42 });43 });...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1var wpt = require('wpt.js');2var wpt = new WebPageTest('www.webpagetest.org');3var options = {4};5wpt.initiateFetch(options, function(err, data) {6 if (err) {7 console.log('Error: ' + err);8 } else {9 console.log('Data: ' + data);10 }11});12### WebPageTest(host, port, apiKey, https)13### getLocations(callback)14### getTesters(callback)15### getTestStatus(testId, callback)16### getTestResults(testId, callback)17### getTestResultData(testId, data, callback)

Full Screen

Using AI Code Generation

copy

Full Screen

1var wpt = require('./wpt.js');2var fs = require('fs');3wpt.initiateFetch(url, function(data) {4 fs.writeFile('response.json', JSON.stringify(data), function(err) {5 if (err) throw err;6 console.log('It\'s saved!');7 });8});

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