How to use secondRequest method in wpt

Best JavaScript code snippet using wpt

http2-xhr-test.js

Source:http2-xhr-test.js Github

copy

Full Screen

1/* global console */2var chai = require('chai');3var assert = chai.assert;4/* jshint ignore:start */5if (typeof XMLHttpRequest === 'undefined') {6 XMLHttpRequest = require("xhr2").XMLHttpRequest;7}8/* jshint ignore:end */9require("../lib/http2-cache");10var FormData = require("../lib/form-data").FormData,11 InvalidStateError = require('../lib/errors.js').InvalidStateError,12 getSocketServer = require('./test-utils.js').getSocketServer,13 getConfigServer = require('./test-utils').getConfigServer,14 generateRandAlphaNumStr = require('./test-utils').generateRandAlphaNumStr,15 lengthInUtf8Bytes = require('./test-utils').lengthInUtf8Bytes;16describe('http2-xhr', function () {17 var config = {18 'transport': 'ws://localhost:7081/path',19 'proxy': [20 'http://cache-endpoint2/',21 'http://cache-endpoint3/',22 'http://localhost:7080/path/proxy',23 ]24 };25 var configServer;26 before(function (done) {27 configServer = getConfigServer({28 config: config,29 port: 708030 }, done);31 });32 after(function (done) {33 configServer.close(done);34 });35 var socket;36 var socketOnRequest;37 beforeEach(function (done) {38 socketOnRequest = function (request, response) {39 throw new Error("socketOnRequest Unexpected request: " + request.url);40 };41 // start config http2 server42 socket = getSocketServer({43 port: 708144 }, function (request, response) {45 socketOnRequest(request, response);46 }, done);47 });48 afterEach(function (done) {49 socket.close(done);50 });51 it('should proxy GET request', function (done) {52 var message = "Hello, Dave. You're looking well today.";53 var date = new Date().toString();54 socketOnRequest = function (request, response) {55 // TODO check request headers and requests responses56 assert.equal(request.url, '/path');57 response.setHeader('Content-Type', 'text/html');58 response.setHeader('Content-Length', message.length);59 response.setHeader('Cache-Control', 'private, max-age=0');60 response.setHeader('date', date);61 response.write(message);62 response.end();63 };64 XMLHttpRequest.proxy(["http://localhost:7080/config"]);65 var xhr = new XMLHttpRequest();66 var statechanges = 0;67 xhr.onreadystatechange = function () {68 ++statechanges;69 // TODO !==1 is due to bug70 if(statechanges !== 1){71 assert.equal(statechanges, xhr.readyState);72 }73 if (xhr.readyState >= 2) {74 assert.equal(xhr.status, 200);75 assert.equal(xhr.statusText, "OK");76 }77 if (xhr.readyState >= 3) {78 assert.equal(xhr.response, message);79 }80 if (xhr.readyState === 4 && xhr.status === 200) {81 assert.equal(xhr.getResponseHeader('content-type'), 'text/html');82 assert.equal(xhr.getAllResponseHeaders(), 'content-type: text/html\ncontent-length: ' + message.length + '\ncache-control: private, max-age=0\ndate: ' + date);83 done();84 }85 };86 xhr.open('GET', 'http://cache-endpoint2/path', true);87 xhr.send(null);88 });89 it('should receive trailer headers', function (done) {90 var message = "Hello, Akram. You're looking well today.";91 var date = new Date().toString();92 var responseTrailers = { 'etag': '123123' };93 socketOnRequest = function (request, response) {94 // TODO check request headers and requests responses95 assert.equal(request.url, '/trailers');96 response.setHeader('Content-Type', 'text/html');97 response.setHeader('Content-Length', message.length);98 response.setHeader('Cache-Control', 'private, max-age=0');99 response.setHeader('date', date);100 response.write(message);101 response.addTrailers(responseTrailers);102 response.end();103 };104 XMLHttpRequest.proxy(["http://localhost:7080/config"]);105 var xhr = new XMLHttpRequest();106 var statechanges = 0;107 xhr.onreadystatechange = function () {108 ++statechanges;109 // TODO !==1 is due to bug110 if(statechanges !== 1){111 assert.equal(statechanges, xhr.readyState);112 }113 if (xhr.readyState >= 2) {114 assert.equal(xhr.status, 200);115 assert.equal(xhr.statusText, "OK");116 }117 if (xhr.readyState >= 3) {118 assert.equal(xhr.response, message);119 }120 if (xhr.readyState === 4 && xhr.status === 200) {121 assert.equal(xhr.getResponseHeader('etag'), '123123');122 assert.equal(xhr.getAllResponseHeaders(), 'content-type: text/html\ncontent-length: ' + message.length + '\ncache-control: private, max-age=0\ndate: ' + date + '\netag: 123123');123 done();124 }125 };126 xhr.open('GET', 'http://cache-endpoint2/trailers', true);127 xhr.send(null);128 });129 it('should timeout proxyfied GET request', function (done) {130 var date = new Date().toString(),131 requestCount = 0,132 timeout = 100;133 socketOnRequest = function (request, response) {134 if (++requestCount === 1) {135 // Will be sent to late.136 setTimeout(function () {137 var message = '{"date": ' + Date.now() + '};';138 assert.equal(request.url, '/path/proxy');139 response.setHeader('Content-Type', 'application/json');140 response.setHeader('Content-Length', message.length);141 response.setHeader('Cache-Control', 'private, max-age=0');142 response.setHeader('date', date);143 response.write(message);144 response.end();145 }, timeout + 1);146 } else {147 throw new Error("Should only get 1 request");148 }149 };150 XMLHttpRequest.proxy(["http://localhost:7080/config"]);151 var xhr = new XMLHttpRequest();152 var statechanges = 0;153 xhr.onreadystatechange = function () {154 ++statechanges;155 if (xhr.readyState >= 2) {156 assert.equal(xhr.status, 0);157 assert.equal(xhr.statusText, "");158 }159 if (xhr.readyState === 4) {160 throw new Error("Should not call onreadystatechange readyState 4");161 }162 };163 xhr.ontimeout = function () {164 assert.equal(xhr.response, null);165 // Make sure xhr.readyState === 4 is never called166 setTimeout(done, 100);167 };168 xhr.open('GET', 'http://localhost:7080/path/proxy', true);169 xhr.timeout = timeout;170 xhr.send(null);171 });172 it('should proxy GET request with event listeners', function (done) {173 var message = "Hello, Dave. You're looking well today.";174 socketOnRequest = function (request, response) {175 // TODO check request headers and requests responses176 assert.equal(request.url, '/withListeners');177 response.setHeader('Content-Type', 'text/html');178 response.setHeader('Content-Length', message.length);179 response.setHeader('Cache-Control', 'private, max-age=0');180 response.write(message);181 response.end();182 };183 XMLHttpRequest.proxy(["http://localhost:7080/config"]);184 var xhr = new XMLHttpRequest();185 xhr.onloadstart = function () {186 xhr.onprogress = function () {187 xhr.onload = function () {188 assert.equal(xhr.status, 200);189 assert.equal(xhr.statusText, "OK");190 xhr.onloadend = function () {191 assert.equal(xhr.response, message);192 done();193 };194 };195 };196 };197 xhr.open('GET', 'http://cache-endpoint2/withListeners', true);198 xhr.send(null);199 });200 201 it('should proxy GET request status', function (done) {202 var message = "Hello, Dave. You're looking well today.";203 socketOnRequest = function (request, response) {204 // TODO check request headers and requests responses205 assert.equal(request.url, '/pathNotFound');206 response.writeHead(404, {207 'Content-Type': 'text/html',208 'Content-Length': message.length209 });210 response.write(message);211 response.end();212 };213 XMLHttpRequest.proxy(["http://localhost:7080/config"]);214 var xhr = new XMLHttpRequest();215 var statechanges = 0;216 xhr.onreadystatechange = function () {217 ++statechanges;218 // TODO !==1 is due to bug219 if(statechanges !== 1){220 assert.equal(statechanges, xhr.readyState);221 }222 if (xhr.readyState >= 2) {223 assert.equal(xhr.status, 404);224 assert.equal(xhr.statusText, "Not Found");225 }226 // TODO assert message227 if (xhr.readyState >= 3) {228 assert.equal(xhr.response, message);229 }230 if (xhr.readyState === 4 && xhr.status === 404) {231 //assert.equal(xhr.getResponseHeader('content-type'), 'text/html');232 //assert.equal(xhr.getAllResponseHeaders()['content-type'], 'text/html');233 done();234 }235 };236 xhr.open('GET', 'http://cache-endpoint2/pathNotFound', true);237 xhr.send(null);238 });239 it('should proxy POST request with event listeners', function (done) {240 var message = "Hello, Dave. You're looking well today.";241 socketOnRequest = function (request, response) {242 // TODO check request headers and requests responses243 assert.equal(request.url, '/payload');244 assert.equal(request.headers['content-type'], 'application/x-www-form-urlencoded');245 assert.equal(request.method, 'POST');246 247 var body = [];248 request.on('data', function(chunk) {249 body.push(chunk);250 }).on('end', function() {251 // at this point, `body` has the entire request body stored in it as a string252 body = Buffer.concat(body).toString();253 response.setHeader('Content-Type', 'text/html');254 response.setHeader('Content-Length', message.length);255 response.setHeader('Cache-Control', 'private, max-age=0');256 response.write(body);257 response.end();258 });259 };260 XMLHttpRequest.proxy(["http://localhost:7080/config"]);261 var xhr = new XMLHttpRequest();262 xhr.onloadstart = function () {263 xhr.onprogress = function () {264 xhr.onload = function () {265 assert.equal(xhr.status, 200);266 assert.equal(xhr.statusText, "OK");267 xhr.onloadend = function () {268 assert.equal(xhr.response, message);269 done();270 };271 };272 };273 };274 xhr.open('POST', 'http://cache-endpoint2/payload', true);275 xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');276 xhr.send(message);277 });278 it('should only proxy path match GET requests', function (done) {279 XMLHttpRequest.proxy(["http://localhost:7080/config"]);280 var message = "Affirmative, Dave. I read you. ";281 var requestCount = 0;282 socketOnRequest = function (request, response) {283 if (++requestCount === 1) {284 // TODO check request headers and requests responses285 assert.equal(request.url, '/path/proxy');286 response.setHeader('Content-Type', 'text/html');287 response.setHeader('Content-Length', message.length);288 response.setHeader('Cache-Control', 'private, max-age=5');289 response.write(message);290 response.end();291 } else {292 throw new Error("Should only proxy '/path/proxy' not '" + request.url + "'");293 }294 };295 var xhr = new XMLHttpRequest();296 var xhr2 = new XMLHttpRequest();297 var doneCnt = 0;298 function doneN(n) {299 if (++doneCnt === n) {300 done();301 }302 }303 var statechanges = 0;304 xhr.onreadystatechange = function () {305 if (xhr.readyState >= 2) {306 assert.equal(200, xhr.status);307 assert.equal("OK", xhr.statusText);308 }309 if (xhr.readyState === 4 && xhr.status === 200) {310 doneN(3);311 }312 };313 xhr.onloadstart = function () {314 xhr.onprogress = function () {315 xhr.onload = function () {316 xhr.onloadend = function () {317 doneN(3);318 };319 };320 };321 };322 var statechangesocket = 0;323 xhr2.onreadystatechange = function () {324 assert.equal(xhr2.readyState, statechangesocket++);325 if (xhr2.readyState >= 2) {326 assert.equal(xhr2.status, 200);327 assert.equal(xhr2.statusText, "OK");328 }329 if (xhr2.readyState === 4 && xhr2.status === 200) {330 xhr2.addEventListener('load', function () {331 doneN(3);332 });333 }334 };335 xhr.open('GET', 'http://localhost:7080/path/proxy', true);336 xhr.send(null);337 xhr2.open('GET', 'http://localhost:7080/path/notproxy?query=1', true);338 xhr2.send(null);339 });340 it('should only proxy path match POST requests (application/x-www-form-urlencoded)', function (done) {341 XMLHttpRequest.proxy(["http://localhost:7080/config"]);342 343 var formData = {344 username: "Chris",345 lastname: "Bob",346 gender: "male",347 };348 var requestCount = 0;349 socketOnRequest = function (request, response) {350 if (++requestCount === 1) {351 assert.equal(request.url, '/path/proxy');352 assert.equal(request.method, 'POST');353 var body = [];354 request.on('data', function(chunk) {355 body.push(chunk);356 }).on('end', function() {357 // at this point, `body` has the entire request body stored in it as a string358 body = Buffer.concat(body).toString();359 assert.equal("username=Chris&lastname=Bob&gender=male", body);360 response.setHeader('Content-Type', 'text/html');361 response.setHeader('Content-Length', body.length);362 response.setHeader('Cache-Control', 'private, max-age=0');363 response.write(body);364 response.end();365 });366 } else {367 throw new Error("Should only proxy '/path/proxy' not '" + request.url + "'");368 }369 };370 var xhr = new XMLHttpRequest();371 var xhr2 = new XMLHttpRequest();372 var doneCnt = 0;373 function doneN(n) {374 if (++doneCnt === n) {375 done();376 }377 }378 var statechanges = 0;379 xhr.onreadystatechange = function () {380 if (xhr.readyState >= 2) {381 assert.equal(200, xhr.status);382 assert.equal("OK", xhr.statusText);383 }384 if (xhr.readyState === 4 && xhr.status === 200) {385 assert.equal("username=Chris&lastname=Bob&gender=male", xhr.responseText);386 doneN(3);387 }388 };389 xhr.onloadstart = function () {390 xhr.onprogress = function () {391 xhr.onload = function () {392 xhr.onloadend = function () {393 doneN(3);394 };395 };396 };397 };398 var statechangesocket = 0;399 xhr2.onreadystatechange = function () {400 assert.equal(xhr2.readyState, statechangesocket++);401 if (xhr2.readyState >= 2) {402 assert.equal(xhr2.status, 200);403 assert.equal(xhr2.statusText, "OK");404 }405 if (xhr2.readyState === 4 && xhr2.status === 200) {406 xhr2.addEventListener('load', function () {407 assert.equal("username=Chris&lastname=Bob&gender=male", xhr2.responseText);408 doneN(3);409 });410 }411 }; 412 xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');413 xhr.open('POST', 'http://localhost:7080/path/proxy', true);414 xhr.send(formData);415 xhr2.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');416 xhr2.open('POST', 'http://localhost:7080/path/notproxy?query=1', true);417 xhr2.send(formData);418 });419 it('should only proxy path match POST requests (multipart/form-data)', function (done) {420 XMLHttpRequest.proxy(["http://localhost:7080/config"]);421 422 var formData = new FormData();423 formData.append('username', 'Chris');424 formData.append('lastname', 'Bob');425 formData.append('gender', 'male'); 426 var seed = formData._TestBoundary = (+(new Date()) + 3).toString(16);427 var requestCount = 0;428 socketOnRequest = function (request, response) {429 if (++requestCount === 1) {430 assert.equal(request.url, '/path/proxy');431 assert.equal(request.method, 'POST');432 var body = [];433 request.on('data', function(chunk) {434 body.push(chunk);435 }).on('end', function() {436 // at this point, `body` has the entire request body stored in it as a string437 body = Buffer.concat(body).toString();438 assert.equal('\r\n------webkitformboundary' + seed + 439 '\r\nContent-Disposition: form-data; name="username"\r\n\r\nChris\r\n------webkitformboundary' + seed + 440 '\r\nContent-Disposition: form-data; name="lastname"\r\n\r\nBob\r\n------webkitformboundary' + seed + 441 '\r\nContent-Disposition: form-data; name="gender"\r\n\r\nmale\r\n------webkitformboundary' + seed + '--', body);442 response.setHeader('Content-Type', 'text/html');443 response.setHeader('Content-Length', body.length);444 response.setHeader('Cache-Control', 'private, max-age=0');445 response.write(body);446 response.end();447 });448 } else {449 throw new Error("Should only proxy '/path/proxy' not '" + request.url + "'");450 }451 };452 var xhr = new XMLHttpRequest();453 var xhr2 = new XMLHttpRequest();454 var doneCnt = 0;455 function doneN(n) {456 if (++doneCnt === n) {457 done();458 }459 }460 var statechanges = 0;461 xhr.onreadystatechange = function () {462 if (xhr.readyState >= 2) {463 assert.equal(200, xhr.status);464 assert.equal("OK", xhr.statusText);465 }466 if (xhr.readyState === 4 && xhr.status === 200) {467 assert.equal('\r\n------webkitformboundary' + seed + 468 '\r\nContent-Disposition: form-data; name="username"\r\n\r\nChris\r\n------webkitformboundary' + seed + 469 '\r\nContent-Disposition: form-data; name="lastname"\r\n\r\nBob\r\n------webkitformboundary' + seed + 470 '\r\nContent-Disposition: form-data; name="gender"\r\n\r\nmale\r\n------webkitformboundary' + seed + '--', xhr.responseText);471 doneN(2);472 }473 };474 xhr.onloadstart = function () {475 xhr.onprogress = function () {476 xhr.onload = function () {477 xhr.onloadend = function () {478 doneN(2);479 };480 };481 };482 };483 484 xhr.open('POST', 'http://localhost:7080/path/proxy', true);485 xhr.send(formData);486 });487 it('should cache GET request and reuse (with default port)', function (done) {488 var message = "Hello, Dave. You're looking well today.";489 var requestCount = 0;490 socketOnRequest = function (request, response) {491 if (++requestCount === 1) {492 // TODO check request headers and requests responses493 assert.equal(request.url, '/cachedGetRequest');494 response.setHeader('Content-Type', 'text/html');495 response.setHeader('Content-Length', message.length);496 response.setHeader('Cache-Control', 'private, max-age=5');497 response.write(message);498 response.end();499 } else {500 throw new Error("Should only get 1 request");501 }502 };503 XMLHttpRequest.proxy(["http://localhost:7080/config"]);504 var firstRequest = new XMLHttpRequest();505 var statechanges = 0;506 firstRequest.onreadystatechange = function () {507 ++statechanges;508 if(statechanges !== 1) {509 assert.equal(statechanges, firstRequest.readyState);510 }511 if (firstRequest.readyState >= 2) {512 assert.equal(firstRequest.status, 200);513 assert.equal(firstRequest.statusText, "OK");514 }515 if (firstRequest.readyState >= 3) {516 assert.equal(firstRequest.response, message);517 }518 if (firstRequest.readyState === 4 && firstRequest.status === 200) {519 var secondRequest = new XMLHttpRequest();520 var statechangesocket = 0;521 secondRequest.onreadystatechange = function () {522 ++statechangesocket;523 // TODO !==1 is due to bug524 if(statechangesocket !== 1) {525 assert.equal(statechangesocket, secondRequest.readyState);526 }527 if (secondRequest.readyState >= 2) {528 assert.equal(secondRequest.status, 200);529 assert.equal(secondRequest.statusText, "OK");530 }531 if (secondRequest.readyState >= 3) {532 assert.equal(secondRequest.response, message);533 }534 if (secondRequest.readyState === 4 && secondRequest.status === 200) {535 assert.equal(secondRequest.response, message);536 done();537 }538 };539 secondRequest.open('GET', 'http://cache-endpoint2/cachedGetRequest', true);540 secondRequest.send(null);541 }542 };543 firstRequest.open('GET', 'http://cache-endpoint2/cachedGetRequest', true);544 firstRequest.send(null);545 });546 it('should cache GET request and reuse (with port)', function (done) {547 var message = "Hello, Dave. You're looking well today.";548 var requestCount = 0;549 socketOnRequest = function (request, response) {550 if (++requestCount === 1) {551 // TODO check request headers and requests responses552 assert.equal(request.url, '/cachedGetRequestWithPort');553 response.setHeader('Content-Type', 'text/html');554 response.setHeader('Content-Length', message.length);555 response.setHeader('Cache-Control', 'private, max-age=5');556 response.write(message);557 response.end();558 } else {559 throw new Error("Should only get 1 request");560 }561 };562 XMLHttpRequest.proxy(["http://localhost:7080/config"]);563 var firstRequest = new XMLHttpRequest();564 var statechanges = 0;565 firstRequest.onreadystatechange = function () {566 ++statechanges;567 if(statechanges !== 1) {568 assert.equal(statechanges, firstRequest.readyState);569 }570 if (firstRequest.readyState >= 2) {571 assert.equal(firstRequest.status, 200);572 assert.equal(firstRequest.statusText, "OK");573 }574 if (firstRequest.readyState >= 3) {575 assert.equal(firstRequest.response, message);576 }577 if (firstRequest.readyState === 4 && firstRequest.status === 200) {578 assert.equal(firstRequest.response, message);579 var secondRequest = new XMLHttpRequest();580 var statechangesocket = 0;581 secondRequest.onreadystatechange = function () {582 ++statechangesocket;583 // TODO !==1 is due to bug584 if(statechangesocket !== 1) {585 assert.equal(statechangesocket, secondRequest.readyState);586 }587 if (secondRequest.readyState >= 2) {588 assert.equal(secondRequest.status, 200);589 assert.equal(secondRequest.statusText, "OK");590 }591 if (secondRequest.readyState >= 3) {592 assert.equal(secondRequest.response, message);593 }594 if (secondRequest.readyState === 4 && secondRequest.status === 200) {595 assert.equal(secondRequest.response, message);596 done();597 }598 };599 secondRequest.open('GET', 'http://cache-endpoint2:80/cachedGetRequestWithPort', true);600 secondRequest.send(null);601 }602 };603 firstRequest.open('GET', 'http://cache-endpoint2:80/cachedGetRequestWithPort', true);604 firstRequest.send(null);605 });606 it('should not cache GET request and not reuse if error', function (done) {607 var messages = [608 "Hello, Dave. You're looking well today.",609 "Do you want to be my friend, Dave ?",610 "Affirmative, Dave. I read you. "611 ];612 var requestCount = 0;613 socketOnRequest = function (request, response) {614 requestCount++;615 if (requestCount === 1) {616 // TODO check request headers and requests responses617 assert.equal(request.url, '/cachedGetRequestWithError');618 response.writeHead(404, {619 'Content-Type': 'text/html',620 'Content-Length': messages[0].length621 });622 response.write(messages[0]);623 response.end();624 } else if (requestCount === 2) {625 // TODO check request headers and requests responses626 assert.equal(request.url, '/cachedGetRequestWithError');627 response.setHeader('Content-Type', 'text/html');628 response.setHeader('Content-Length', messages[1].length);629 response.setHeader('Cache-Control', 'private, max-age=5');630 response.write(messages[1]);631 response.end();632 } else {633 throw new Error("Should only get 2 request");634 }635 };636 XMLHttpRequest.proxy(["http://localhost:7080/config"]);637 var firstRequest = new XMLHttpRequest();638 var statechanges = 0;639 firstRequest.onreadystatechange = function () {640 ++statechanges;641 if(statechanges !== 1) {642 assert.equal(statechanges, firstRequest.readyState);643 }644 if (firstRequest.readyState >= 2) {645 assert.equal(firstRequest.status, 404);646 assert.equal(firstRequest.statusText, "Not Found");647 }648 if (firstRequest.readyState >= 3) {649 assert.equal(firstRequest.response, messages[0]);650 }651 if (firstRequest.readyState === 4 && firstRequest.status === 404) {652 assert.equal(firstRequest.response, messages[0]);653 var secondRequest = new XMLHttpRequest();654 var statechangesocket = 0;655 secondRequest.onreadystatechange = function () {656 ++statechangesocket;657 // TODO !==1 is due to bug658 if(statechangesocket !== 1) {659 assert.equal(statechangesocket, secondRequest.readyState);660 }661 if (secondRequest.readyState >= 2) {662 assert.equal(secondRequest.status, 200);663 assert.equal(secondRequest.statusText, "OK");664 }665 if (secondRequest.readyState >= 3) {666 assert.equal(secondRequest.response, messages[1]);667 }668 if (secondRequest.readyState === 4 && secondRequest.status === 200) {669 assert.equal(secondRequest.response, messages[1]);670 done();671 }672 };673 secondRequest.open('GET', 'http://cache-endpoint2:80/cachedGetRequestWithError', true);674 secondRequest.send(null);675 }676 };677 firstRequest.open('GET', 'http://cache-endpoint2:80/cachedGetRequestWithError', true);678 firstRequest.send(null);679 });680 it('should return responseType when proxyfied', function (done) {681 var message = '{"message": "Hello, Dave. You\'re looking well today."}';682 var date = new Date().toString();683 var responseTypes = [684 {685 requestType: 'arraybuffer',686 responseType: 'ArrayBuffer'687 },688 {689 requestType: 'text',690 responseType: 'String'691 },692 {693 requestType: 'json',694 responseType: 'Object'695 },696 /*697 {698 requestType: 'blob',699 responseType: 'Blob'700 },701 {702 requestType: 'document',703 responseType: 'HTMLNode'704 }705 */706 ];707 socketOnRequest = function (request, response) {708 // TODO check request headers and requests responses709 assert.equal(request.url, '/path/proxy/responseType');710 response.setHeader('Content-Type', 'application/json');711 response.setHeader('Content-Length', message.length);712 response.setHeader('Cache-Control', 'private, max-age=0');713 response.setHeader('date', date);714 response.write(message);715 response.end();716 };717 var doneCnt = 0;718 function doneN(n) {719 if (++doneCnt === n) {720 done();721 }722 }723 responseTypes.forEach(function (assertType) {724 XMLHttpRequest.proxy(["http://localhost:7080/config"]);725 var xhr = new XMLHttpRequest();726 var statechanges = 0;727 xhr.onreadystatechange = function () {728 ++statechanges;729 if (xhr.readyState >= 2) {730 assert.equal(xhr.status, 200);731 assert.equal(xhr.statusText, "OK");732 }733 if (xhr.readyState === 4 && xhr.status === 200) {734 assert.equal(xhr.responseType, assertType.requestType);735 assert.equal(xhr.response.constructor.name, assertType.responseType);736 doneN(responseTypes.length);737 }738 };739 xhr.open('GET', 'http://localhost:7080/path/proxy/responseType', true);740 xhr.responseType = assertType.requestType;741 xhr.send(null);742 });743 });744 /* Ignoring the test since we removed the code where we are throwing an exception745 it('should return Throw InvalidStateError when responseText is used with invalid responseType', function (done) {746 747 var message = '{"message": "Hello, Dave. You\'re looking well today."}';748 var date = new Date().toString();749 socketOnRequest = function (request, response) {750 // TODO check request headers and requests responses751 assert.equal(request.url, '/path/proxy/responseTypeBadText');752 response.setHeader('Content-Type', 'application/json');753 response.setHeader('Content-Length', message.length);754 response.setHeader('Cache-Control', 'private, max-age=0');755 response.setHeader('date', date);756 response.write(message);757 response.end();758 };759 XMLHttpRequest.proxy(["http://localhost:7080/config"]);760 var xhr = new XMLHttpRequest();761 var statechanges = 0;762 xhr.onreadystatechange = function () {763 ++statechanges;764 if (xhr.readyState >= 2) {765 assert.equal(xhr.status, 200);766 assert.equal(xhr.statusText, "OK");767 }768 if (xhr.readyState === 4 && xhr.status === 200) {769 assert.equal(xhr.responseType, 'json');770 assert.equal(typeof xhr.response, 'object');771 try {772 var responseText = xhr.responseText;773 } catch (err) {774 assert.equal(err instanceof InvalidStateError, true);775 done(); 776 }777 }778 };779 780 xhr.open('GET', 'http://localhost:7080/path/proxy/responseTypeBadText', true);781 xhr.responseType = 'json';782 xhr.send(null);783 });784 */785 it('should return responseType when NOT proxyfied', function (done) {786 var date = new Date().toString();787 var responseTypes = [788 {789 requestType: 'arraybuffer',790 responseType: 'ArrayBuffer'791 },792 {793 requestType: 'text',794 responseType: 'String'795 },796 {797 requestType: 'json',798 responseType: 'Object'799 },800 /*801 {802 requestType: 'blob',803 responseType: 'Blob'804 },805 {806 requestType: 'document',807 responseType: 'HTMLNode'808 }809 */810 ];811 socketOnRequest = function (request, response) {812 throw new Error("Should only proxy '/path/proxy' not '" + request.url + "'");813 };814 var doneCnt = 0;815 function doneN(n) {816 if (++doneCnt === n) {817 done();818 }819 }820 responseTypes.forEach(function (assertType) {821 XMLHttpRequest.proxy(["http://localhost:7080/config"]);822 var xhr = new XMLHttpRequest();823 var statechanges = 0;824 xhr.onreadystatechange = function () {825 ++statechanges;826 if (xhr.readyState >= 2) {827 assert.equal(xhr.status, 200);828 assert.equal(xhr.statusText, "OK");829 }830 if (xhr.readyState === 4 && xhr.status === 200) {831 assert.equal(assertType.requestType, xhr.responseType);832 assert.equal(assertType.responseType, xhr.response.constructor.name);833 doneN(responseTypes.length);834 }835 };836 xhr.open('GET', 'http://localhost:7080/path/responseType', true);837 xhr.responseType = assertType.requestType;838 xhr.send(null);839 });840 });841 it('should cache GET request and reuse for response larger than MAX_PAYLOAD_SIZE', function (done) {842 var requestCount = 0;843 var MAX_PAYLOAD_SIZE = 4096;844 var length = MAX_PAYLOAD_SIZE * 10;845 var message = generateRandAlphaNumStr(length);846 socketOnRequest = function (request, response) {847 if (++requestCount === 1) {848 // TODO check request headers and requests responses849 assert.equal(request.url, '/cachedGetLargeRequest');850 response.setHeader('Content-Type', 'text/html');851 response.setHeader('Content-Length', lengthInUtf8Bytes(message));852 response.setHeader('Cache-Control', 'private, max-age=5');853 response.write(message);854 response.end();855 } else {856 throw new Error("Should only get 1 request");857 }858 };859 XMLHttpRequest.proxy(["http://localhost:7080/config"]);860 var firstRequest = new XMLHttpRequest();861 var statechanges = 0;862 var loadingchanges = 0,863 framesSizes = [];864 firstRequest.onreadystatechange = function () {865 ++statechanges;866 if (firstRequest.readyState >= 2) {867 assert.equal(firstRequest.status, 200);868 assert.equal(firstRequest.statusText, "OK");869 }870 if (firstRequest.readyState === 3) {871 framesSizes.push(firstRequest.responseText.length);872 loadingchanges++;873 }874 if (firstRequest.readyState === 4 && firstRequest.status === 200) {875 var secondRequest = new XMLHttpRequest();876 var statechangesocket = 0;877 secondRequest.onreadystatechange = function () {878 ++statechangesocket;879 if(statechangesocket !== 1) {880 assert.equal(statechangesocket, secondRequest.readyState);881 }882 if (secondRequest.readyState >= 2) {883 assert.equal(secondRequest.status, 200);884 assert.equal(secondRequest.statusText, "OK");885 }886 // Expect cached frame and to only append once887 if (secondRequest.readyState === 3) {888 // Should match last decoded size from firstRequest889 assert.equal(framesSizes[loadingchanges - 1], secondRequest.responseText.length);890 // Catch double secondRequest.readyState === 3 by making test above fail subsequently891 loadingchanges = -1;892 }893 if (secondRequest.readyState === 4 && secondRequest.status === 200) {894 assert.equal(secondRequest.responseText, message);895 assert.equal(secondRequest.responseText.length, message.length);896 assert.equal(secondRequest.response, secondRequest.responseText);897 done();898 }899 };900 secondRequest.open('GET', 'http://cache-endpoint2/cachedGetLargeRequest', true);901 secondRequest.send(null);902 }903 };904 firstRequest.open('GET', 'http://cache-endpoint2/cachedGetLargeRequest', true);905 firstRequest.send(null);906 // This test should take between 2000ms and 3000ms timeout above can be a sign of performance regression.907 }).timeout(10000);...

Full Screen

Full Screen

test.fetch.js

Source:test.fetch.js Github

copy

Full Screen

1'use strict'2/* eslint-env jest */3/*4 Functional Testing:5 FireFerret's Fetch functionality6*/7const { PassThrough } = require('stream')8const { MongoMemoryServer } = require('mongodb-memory-server')9const { createClient } = require('redis-mock')10const FireFerret = require('../../lib/client')11/* using default docs scheme from https://www.npmjs.com/package/mockuments */12const printer = require('mockuments')13const deepClone = require('clone-deep')14let ferret15let mongoServer16let redis17let docs18let ids19const collections = {}20beforeAll(async (done) => {21 jest.setTimeout(120000)22 collections.one = { content: printer(1000), name: 'one', ids: null }23 collections.two = { content: printer(1000), name: 'two', ids: null }24 redis = createClient()25 mongoServer = new MongoMemoryServer()26 const uri = await mongoServer.getConnectionString()27 const opts = {28 mongo: { uri, collectionName: collections.one.name },29 redis: {}30 }31 ferret = new FireFerret(opts)32 ferret.cache._setClient(redis)33 await ferret.connect()34 const mongo = ferret.mongo._getClient()35 const { insertedIds: batchOneIds } = await mongo36 .db()37 .collection(collections.one.name)38 .insertMany(collections.one.content)39 const { insertedIds: batchTwoIds } = await mongo40 .db()41 .collection(collections.two.name)42 .insertMany(collections.two.content)43 collections.one.ids = Object.values(batchOneIds)44 collections.two.ids = Object.values(batchTwoIds)45 done()46})47afterAll(async (done) => {48 await ferret.close()49 await mongoServer.stop()50 redis.quit()51 done()52})53describe('fetch', function () {54 it('should return hydrated documents using the default query', async function (done) {55 const query = undefined56 const queryOptions = { hydrate: true }57 const expected = deepClone(collections.one.content)58 const firstRequest = await ferret.fetch(query, queryOptions)59 expect(firstRequest.length).toEqual(expected.length)60 expect(firstRequest).toEqual(expected)61 const secondRequest = await ferret.fetch(query, queryOptions)62 expect(secondRequest.length).toEqual(expected.length)63 expect(secondRequest).toEqual(expected)64 done()65 })66 it('should return documents without hydrating', async function (done) {67 const query = undefined68 const queryOptions = undefined69 /* first request cache-misses; thus the return is already hydrated from Mongo */70 const expectedFirst = deepClone(collections.one.content)71 const expectedSecond = JSON.parse(JSON.stringify(collections.one.content))72 const firstRequest = await ferret.fetch(query, queryOptions)73 expect(firstRequest).toEqual(expectedFirst)74 const secondRequest = await ferret.fetch(query, queryOptions)75 expect(secondRequest).toEqual(expectedSecond)76 done()77 })78 it('should return hydrated documents that match a query', async function (done) {79 const query = { 'contact.onEarth': true }80 const queryOptions = { hydrate: true }81 const expected = deepClone(collections.one.content).filter(82 (v) => v.contact.onEarth === true83 )84 const firstRequest = await ferret.fetch(query, queryOptions)85 expect(firstRequest).toEqual(expected)86 const secondRequest = await ferret.fetch(query, queryOptions)87 expect(secondRequest).toEqual(expected)88 done()89 })90 it('should obey pagination rules with size of 1', async function (done) {91 const query = {}92 const queryOptions = { hydrate: true, pagination: { page: 1, size: 1 } }93 const expected = deepClone(collections.one.content).slice(0, 1)94 const firstRequest = await ferret.fetch(query, queryOptions)95 expect(expected.length).toEqual(firstRequest.length)96 expect(firstRequest).toEqual(expected)97 const secondRequest = await ferret.fetch(query, queryOptions)98 expect(expected.length).toEqual(secondRequest.length)99 expect(secondRequest).toEqual(expected)100 done()101 })102 it('should obey pagination rules', async function (done) {103 const query = {}104 const queryOptions = {105 hydrate: true,106 pagination: {107 page: 1,108 size: Math.floor(collections.one.content.length / 2)109 }110 }111 const expected = deepClone(collections.one.content).slice(112 0,113 Math.floor(collections.one.content.length / 2)114 )115 const firstRequest = await ferret.fetch(query, queryOptions)116 expect(expected.length).toEqual(firstRequest.length)117 expect(firstRequest).toEqual(expected)118 const secondRequest = await ferret.fetch(query, queryOptions)119 expect(expected.length).toEqual(secondRequest.length)120 expect(secondRequest).toEqual(expected)121 done()122 })123 it('should return a stream when using the queryOptions.stream', async function (done) {124 const query = {}125 const queryOptions = { stream: true }126 const expected = JSON.parse(JSON.stringify(collections.one.content))127 const stream = await ferret.fetch(query, queryOptions)128 expect(stream.constructor).toBe(PassThrough)129 let chunks = ''130 stream.on('data', (chunk) => (chunks += chunk))131 stream.on('end', () => {132 const actual = JSON.parse(chunks)133 expect(actual).toEqual(expected)134 done()135 })136 })137 it('should return a stream that obeys pagination when using the queryOptions.stream', async function (done) {138 const query = {}139 const queryOptions = { stream: true, pagination: { page: 1, size: 5 } }140 const expected = JSON.parse(JSON.stringify(collections.one.content)).slice(141 0,142 5143 )144 const stream = await ferret.fetch(query, queryOptions)145 expect(stream.constructor).toBe(PassThrough)146 let chunks = ''147 stream.on('data', (chunk) => (chunks += chunk))148 stream.on('end', () => {149 const actual = JSON.parse(chunks)150 expect(actual).toEqual(expected)151 done()152 })153 })154 it('should return a stream from the specified collection.', async function (done) {155 const query = {}156 const queryOptions = { stream: true }157 const collectionName = collections.two.name158 const expected = JSON.parse(JSON.stringify(collections.two.content))159 const stream = await ferret.fetch(query, queryOptions, collectionName)160 expect(stream.constructor).toBe(PassThrough)161 let chunks = ''162 stream.on('data', (chunk) => (chunks += chunk))163 stream.on('end', () => {164 const actual = JSON.parse(chunks)165 expect(actual).toEqual(expected)166 done()167 })168 })169 it('should return an array of documents from the specified collection.', async function (done) {170 const query = {}171 const queryOptions = {}172 const collectionName = collections.two.name173 const expected = deepClone(collections.two.content)174 const actual = await ferret.fetch(175 query,176 queryOptions,177 collections.two.name178 )179 expect(actual.length).toEqual(expected.length)180 expect(actual).toEqual(expected)181 done()182 })183})184describe('fetchOne', function () {185 it('should return the first hydrated document that matches the query', async function (done) {186 const query = {}187 const queryOptions = { hydrate: true }188 const expected = deepClone(collections.one.content)[0]189 const firstRequest = await ferret.fetchOne(query, queryOptions)190 expect(firstRequest).toEqual(expected)191 const secondRequest = await ferret.fetchOne(query, queryOptions)192 expect(secondRequest).toEqual(expected)193 done()194 })195 it('should return the first document that matches the query', async function (done) {196 const query = {}197 const queryOptions = undefined198 const expected = JSON.parse(JSON.stringify(collections.one.content))[0]199 await ferret.fetchOne(query, queryOptions) /* prime cache */200 const firstRequest = await ferret.fetchOne(query, queryOptions)201 expect(firstRequest).toEqual(expected)202 const secondRequest = await ferret.fetchOne(query, queryOptions)203 expect(secondRequest).toEqual(expected)204 done()205 })206 it('should return the first document from a specified collection', async function (done) {207 const query = {}208 const queryOptions = { hydrate: true }209 const collectionName = collections.two.name210 const expected = deepClone(collections.two.content)[0]211 const firstRequest = await ferret.fetchOne(212 query,213 queryOptions,214 collectionName215 )216 expect(firstRequest).toEqual(expected)217 const secondRequest = await ferret.fetchOne(218 query,219 queryOptions,220 collectionName221 )222 expect(secondRequest).toEqual(expected)223 done()224 })225})226describe('fetchById', function () {227 it('should return a hydrated document with matching _id', async function (done) {228 const id = collections.one.ids[0]229 const queryOptions = { hydrate: true }230 /* gotta add le _id */231 const expected = { ...deepClone(collections.one.content)[0], _id: id }232 const firstRequest = await ferret.fetchById(id, queryOptions)233 expect(firstRequest).toEqual(expected)234 const secondRequest = await ferret.fetchOne(id, queryOptions)235 expect(secondRequest).toEqual(expected)236 done()237 })238 it('should return a document with matching _id', async function (done) {239 const id = collections.one.ids[0]240 const queryOptions = undefined241 /* gotta add le _id */242 const expected = {243 ...JSON.parse(JSON.stringify(collections.one.content))[0],244 _id: id.toHexString()245 }246 const firstRequest = await ferret.fetchById(id, queryOptions)247 expect(firstRequest).toEqual(expected)248 const secondRequest = await ferret.fetchById(id, queryOptions)249 expect(secondRequest).toEqual(expected)250 done()251 })252 it('should return a document from a specified collection.', async function (done) {253 const id = collections.two.ids[0]254 const queryOptions = undefined255 const collectionName = collections.two.name256 /* gotta add le _id */257 const expected = {258 ...JSON.parse(JSON.stringify(collections.two.content))[0],259 _id: id.toHexString()260 }261 const firstRequest = await ferret.fetchById(262 id,263 queryOptions,264 collectionName265 )266 expect(firstRequest).toEqual(expected)267 const secondRequest = await ferret.fetchById(268 id,269 queryOptions,270 collectionName271 )272 expect(secondRequest).toEqual(expected)273 done()274 })...

Full Screen

Full Screen

javaScript.js

Source:javaScript.js Github

copy

Full Screen

1const baseUrl = 'https://api.twitch.tv/kraken'2const topGameArr = []3const htmlTemplate = `4 <div class="single-stream">5 <div class="preview-large" style="background-image: url('$previewLarge')"></div>6 <div class="container">7 <div class="logo" style="background-image: url('$channelLogo')"></div>8 <div class="stream-content">9 <p class="status">$channelStatus</p>10 <p class="display-name">$channelName</p>11 </div>12 </div>13`14getTopGame()15function getTopGame() {16 const request = new XMLHttpRequest()17 const url = `${baseUrl}/games/top?limit=5`18 request.addEventListener('error', (e) => { alert(e.type) })19 request.open('GET', url, true)20 request.setRequestHeader('Accept', 'application/vnd.twitchtv.v5+json')21 request.setRequestHeader('Client-ID', 'qm66ogvzwsxrzkdyrfrxi748glwjo9')22 request.addEventListener('load', (e) => {23 if (request.status >= 400) {24 alertError('handling request/response', request.status)25 }26 let response = ''27 let json = ''28 try {29 response = request.response30 json = JSON.parse(response)31 } catch (error) {32 alert('oops, something went wrong with JSON...')33 return34 }35 for (const each of json.top) {36 topGameArr.push(each.game.name)37 }38 getStreams(topGameArr[0])39 appendNav(topGameArr, getStreams)40 })41 request.send()42}43// ex: getStreams("Just Chatting")44function getStreams(game) {45 const secondRequest = new XMLHttpRequest()46 const url = `${baseUrl}/streams/?game=${game}&limit=20`47 secondRequest.addEventListener('error', (e) => { alert(e.type) })48 secondRequest.open('GET', url, true)49 secondRequest.setRequestHeader('Accept', 'application/vnd.twitchtv.v5+json')50 secondRequest.setRequestHeader('Client-ID', 'qm66ogvzwsxrzkdyrfrxi748glwjo9')51 secondRequest.addEventListener('load', (e) => {52 if (secondRequest.status >= 400) {53 alertError('loading streams', secondRequest.status)54 }55 appendGames(game)56 let response = ''57 let json = ''58 try {59 response = secondRequest.response60 json = JSON.parse(response)61 } catch (error) {62 alert('oops, something went wrong with JSON...')63 return64 }65 appendStreams(json)66 })67 secondRequest.send()68}69function alertError(reasonStr, statuscode) { // 處理 statuscode 錯誤的情況70 console.log(`oops, something went wrong while ${reasonStr} ...the statuscode is ${statuscode}`)71 alert(`oops, something went wrong while ${reasonStr} ...the statuscode is ${statuscode}`)72}73function appendNav(gameArr, callback) {74 const navRight = document.querySelector('.nav-right')75 navRight.innerHTML = `76 <li class="active">${gameArr[0]}</li>77 <li>${gameArr[1]}</li>78 <li>${gameArr[2]}</li>79 <li>${gameArr[3]}</li>80 <li>${gameArr[4]}</li>81 `82 for (let i = 0; i < gameArr.length; i++) {83 const navRightLi = document.querySelector(`.nav-right li:nth-child(${i + 1})`)84 navRightLi.addEventListener('click', (e) => {85 callback(gameArr[i])86 document.querySelector('.active').classList.remove('active') // 點選 nav 的遊戲之後, 顏色會變黑底87 e.target.classList.add('active')88 })89 }90}91function appendGames(game) {92 const title = document.querySelector('h1')93 title.innerText = `${game}`94}95function appendStreams(json) {96 const streams = document.querySelector('.streams')97 streams.innerHTML = '' // 點選別的遊戲之後,原本的內容要清空再載入別的遊戲的實況98 for (const each of json.streams) {99 const template = document.createElement('template')100 template.innerHTML = htmlTemplate101 .replace('$previewLarge', each.preview.large)102 .replace('$channelLogo', each.channel.logo)103 .replace('$channelStatus', each.channel.status)104 .replace('$channelName', each.channel.display_name)105 streams.append(template.content)106 }...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1var wpt = function() {2 this.secondRequest = function() {3 };4 this.firstRequest = function() {5 };6 this.thirdRequest = function() {7 };8 this.fourthRequest = function() {9 };10 this.fifthRequest = function() {11 };12 this.sixthRequest = function() {13 };14};15module.exports = wpt;16Your name to display (optional):17Your name to display (optional):18var wpt = function() {19 this.secondRequest = function() {20 };21 this.firstRequest = function() {22 };23 this.thirdRequest = function() {24 };25 this.fourthRequest = function() {26 };27 this.fifthRequest = function() {28 };29 this.sixthRequest = function() {30 };31};32module.exports = new wpt();33Your name to display (optional):

Full Screen

Using AI Code Generation

copy

Full Screen

1var wpt = require('./wpt.js');2 console.log(data);3});4var request = require('request'),5 querystring = require('querystring');6exports.secondRequest = function(url, callback) {7 var options = {8 form: {9 }10 };11 request(options, function(error, response, body) {12 if (!error && response.statusCode == 200) {13 var data = JSON.parse(body);14 var result = data.data.summary;15 callback(result);16 }17 });18};19var express = require('express');20var app = express();21var https = require('https');22var fs = require('fs');23var path = require('path');24var bodyParser = require('body-parser');25var request = require('request');26var url = require('url');27var cheerio = require('cheerio');28var http = require('http');29var json2csv = require('json2csv');30var fields = ['name', 'age'];31app.use(bodyParser.json());32app.use(bodyParser.urlencoded({ extended: true }));33app.get('/test', function(req, res) {34 console.log('test');35 if (err) {36 console.log(err);37 } else {38 console.log(body);39 }40 });41});42app.listen(3000, function() {43 console.log('server started');44});45var request = require('request');46app.post('/api/test', function(req, res)

Full Screen

Using AI Code Generation

copy

Full Screen

1var wpt = require('./wpt.js');2var wpt = new wpt();3wpt.secondRequest(url, function (error, response, body) {4 if (!error && response.statusCode == 200) {5 console.log(body);6 }7});8var request = require('request');9var secondRequest = function (url, callback) {10 request(url, callback);11};12module.exports = secondRequest;13var request = require('request');14request(url, function (error, response, body) {15 if (!error && response.statusCode == 200) {16 console.log(body);17 }18});19var request = require('request');20var secondRequest = function (url, callback) {21 request(url, callback);22};23module.exports = secondRequest;

Full Screen

Using AI Code Generation

copy

Full Screen

1var wpt = require('wpt');2var wpt = new WebPageTest('www.webpagetest.org');3var options = {4};5wpt.runTest(testURL, options, function(err, data) {6 if (err) return console.log(err);7 console.log(data);8});9var testId = data.data.testId;10wpt.getTestResults(testId, function(err, data) {11 if (err) return console.log(err);12 console.log(data);13});14{ statusCode: 400,15 data: 'Missing or invalid test ID' }

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(data);6 }7});8var wpt = require('wpt');9 if(err) {10 console.log('Error: ' + err);11 } else {12 console.log(data);13 }14});15var wpt = require('wpt');16 if(err) {17 console.log('Error: ' + err);18 } else {19 console.log(data);20 }21});22var wpt = require('wpt');23wpt.getLocations(function(err, data) {24 if(err) {25 console.log('Error: ' + err);26 } else {27 console.log(data);28 }29});30var wpt = require('wpt');31wpt.getTesters(function(err, data) {32 if(err) {33 console.log('Error: ' + err);34 } else {35 console.log(data);36 }37});38var wpt = require('wpt');39 if(err) {40 console.log('Error: ' + err);41 } else {42 console.log(data);43 }44});45var wpt = require('wpt');46wpt.getLocations(function(err, data) {47 if(err) {48 console.log('Error: ' + err);49 } else {50 console.log(data);51 }52});53var wpt = require('wpt');54wpt.getTesters(function(err, data) {55 if(err) {56 console.log('Error: ' + err);57 } else {58 console.log(data);59 }60});

Full Screen

Using AI Code Generation

copy

Full Screen

1You can use the require function to import the wpt.js file in test.js, and then use the methods of wpt.js like this:2var wpt = require('./wpt.js');3wpt.firstRequest();4wpt.secondRequest();5You can also use the import keyword in ES6 to import the wpt.js file in test.js, and then use the methods of wpt.js like this:6import wpt from './wpt.js';7wpt.firstRequest();8wpt.secondRequest();9Your name to display (optional):10Your name to display (optional):11If you want to use asynchronous functions, you can use the import keyword to import the wpt.js file in test.js, and then use the methods of wpt.js like this:12import('./wpt.js')13 .then(wpt => {14 wpt.firstRequest();15 wpt.secondRequest();16 });17Your name to display (optional):18You can use the require function to import ...READ MORE

Full Screen

Using AI Code Generation

copy

Full Screen

1var wpt = require('wpt-api');2 console.log(data);3});4var wpt = require('wpt-api');5 console.log(data);6});7var wpt = require('wpt-api');8 console.log(data);9});10var wpt = require('wpt-api');11wpt.getLocations("API_KEY", "xml", function(data){12 console.log(data);13});

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