Best JavaScript code snippet using playwright-internal
utils_request.test.js
Source: utils_request.test.js
1import express from 'express';2import {3 requestAsBrowser,4 FIREFOX_MOBILE_USER_AGENT,5 FIREFOX_DESKTOP_USER_AGENT,6} from '../build/utils_request';7import { startExpressAppPromise } from './_helper';8const CONTENT = 'CONTENT';9const HOSTNAME = '127.0.0.1';10describe('Apify.utils_request', () => {11 let port;12 let server;13 beforeAll(async () => {14 const app = express();15 app.get('/406', (req, res) => {16 res.setHeader('content-type', 'text/html; charset=utf-8');17 res.status(406);18 res.send(CONTENT);19 });20 app.get('/echo', (req, res) => {21 res.send(JSON.stringify(req.headers));22 });23 app.get('/rawHeaders', (req, res) => {24 res.send(JSON.stringify(req.rawHeaders));25 });26 app.get('/invalidContentType', (req, res) => {27 res.setHeader('content-type', 'application/json');28 res.send(CONTENT);29 });30 app.get('/invalidContentHeader', (req, res) => {31 res.setHeader('Content-Type', 'non-existent-content-type');32 res.send(CONTENT);33 });34 app.get('/invalidBody', async (req, res) => {35 res.setHeader('content-encoding', 'deflate');36 res.status(500);37 res.send(Buffer.from(CONTENT, 'utf8'));38 });39 app.get('/empty', async (req, res) => {40 res.setHeader('Content-Type', 'text/html; charset=utf-8');41 res.send();42 });43 app.get('/invalidHeaderChar', (req) => {44 const headers = {45 'Invalid Header With Space': 'some\value',46 'X-Normal-Header': 'HeaderValue2',47 };48 let msg = 'HTTP/1.1 200 OK\r\n';49 Object.entries(headers).forEach(([key, value]) => {50 msg += `${key}: ${value}\r\n`;51 });52 msg += `\r\n${CONTENT}`;53 req.socket.write(msg, () => {54 req.socket.end();55 // Unfortunately calling end() will not close the socket56 // if client refuses to close it. Hence calling destroy after a short while.57 setTimeout(() => {58 req.socket.destroy();59 }, 100);60 });61 });62 server = await startExpressAppPromise(app, 0);63 port = server.address().port; //eslint-disable-line64 });65 afterAll(() => {66 server.close();67 });68 describe('Apify.requestAsBrowser', () => {69 test(70 'it uses mobile user-agent when mobile property is set to true ',71 async () => {72 const data = {73 url: `http://${HOSTNAME}:${port}/echo`,74 useMobileVersion: true,75 };76 const response = await requestAsBrowser(data);77 expect(response.statusCode).toBe(200);78 expect(JSON.parse(response.body)['user-agent']).toEqual(FIREFOX_MOBILE_USER_AGENT);79 },80 );81 test('uses desktop user-agent by default ', async () => {82 const data = {83 url: `http://${HOSTNAME}:${port}/echo`,84 };85 const response = await requestAsBrowser(data);86 expect(response.statusCode).toBe(200);87 expect(JSON.parse(response.body)['user-agent']).toEqual(FIREFOX_DESKTOP_USER_AGENT);88 });89 test('sets correct hosts', async () => {90 const host = `${HOSTNAME}:${port}`;91 const options = {92 url: `http://${host}/echo`,93 };94 const response = await requestAsBrowser(options);95 expect(response.statusCode).toBe(200);96 expect(JSON.parse(response.body).host).toEqual(host);97 });98 test('uses correct default language', async () => {99 const languageCode = 'en';100 const countryCode = 'US';101 const host = `${HOSTNAME}:${port}`;102 const options = {103 url: `http://${host}/echo`,104 };105 const response = await requestAsBrowser(options);106 expect(response.statusCode).toBe(200);107 expect(JSON.parse(response.body)['accept-language']).toEqual(`${languageCode}-${countryCode},${languageCode};q=0.5`);108 });109 test('does not throw for empty response body', async () => {110 const options = {111 url: `http://${HOSTNAME}:${port}/empty`,112 };113 let error;114 try {115 await requestAsBrowser(options);116 } catch (e) {117 error = e;118 }119 expect(error).toBeFalsy(); //eslint-disable-line120 });121 test('overrides defaults', async () => {122 const host = `${HOSTNAME}:${port}`;123 const options = {124 url: `http://${host}/echo`,125 headers: {126 'User-Agent': 'chrome',127 },128 };129 const response = await requestAsBrowser(options);130 expect(response.statusCode).toBe(200);131 expect(JSON.parse(response.body)['user-agent']).toEqual(options.headers['User-Agent']);132 });133 test('headers has same format as in firefox', async () => {134 const host = `${HOSTNAME}:${port}`;135 const options = {136 url: `http://${host}/rawHeaders`,137 };138 const response = await requestAsBrowser(options);139 const headersArray = JSON.parse(response.body);140 expect(response.statusCode).toBe(200);141 expect(headersArray[0]).toBe('Host');142 expect(headersArray[1]).toEqual(host);143 expect(headersArray[2]).toBe('User-Agent');144 expect(headersArray[3]).toEqual(FIREFOX_DESKTOP_USER_AGENT);145 expect(headersArray[4]).toBe('Accept');146 expect(headersArray[5]).toBe('text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8');147 expect(headersArray[6]).toBe('Accept-Language');148 expect(headersArray[7]).toBe('en-US,en;q=0.5');149 expect(headersArray[8]).toBe('Accept-Encoding');150 expect(headersArray[9]).toBe('gzip, deflate, br');151 expect(headersArray[10]).toBe('Connection');152 expect(headersArray[11]).toBe('keep-alive');153 });154 test('custom headers in lowercase override uppercase defaults', async () => {155 const host = `${HOSTNAME}:${port}`;156 const options = {157 url: `http://${host}/rawHeaders`,158 headers: {159 accept: 'foo',160 bar: 'BAZ',161 },162 };163 const response = await requestAsBrowser(options);164 const headersArray = JSON.parse(response.body);165 expect(response.statusCode).toBe(200);166 expect(headersArray[4]).toBe('Accept');167 expect(headersArray[5]).toBe('foo');168 expect(headersArray[12]).toBe('bar');169 expect(headersArray[13]).toBe('BAZ');170 });171 test('correctly handles invalid header characters', async () => {172 const url = `http://${HOSTNAME}:${port}/invalidHeaderChar`;173 const response = await requestAsBrowser({ url });174 expect(response.body).toBe(CONTENT);175 expect(response.headers).toEqual({176 'invalid header with space': 'some\value',177 'x-normal-header': 'HeaderValue2',178 });179 try {180 await requestAsBrowser({181 useInsecureHttpParser: false,182 url,183 });184 } catch (err) {185 if (process.version.startsWith('v10')) {186 expect(err.message).toMatch('Parse Error');187 } else {188 expect(err.message).toMatch('Parse Error: Invalid header value char');189 }190 }191 });192 test('does not get into redirect loops', async () => {193 const url = 'https://www.smartmania.cz'; // uses www to no-www redirect194 try {195 await requestAsBrowser({ url });196 } catch (err) {197 // If it's some other error, it's fine for the purpose of this test.198 // We're only making sure that the max redirect error is not there.199 if (err.name === 'MaxRedirectsError') throw err;200 }201 });202 });...
Bibliotheque et Archives Nationale du Quebec (Pistard).js
Source: Bibliotheque et Archives Nationale du Quebec (Pistard).js
1{2 "translatorID": "1eb5eb03-26ab-4015-bd0d-65487734744a",3 "translatorType": 4,4 "label": "Bibliotheque et Archives Nationale du Quebec (Pistard)",5 "creator": "Adam Crymble",6 "target": "^https?://pistard\\.banq\\.qc\\.ca",7 "minVersion": "1.0.0b4.r5",8 "maxVersion": "",9 "priority": 100,10 "inRepository": true,11 "lastUpdated": "2008-08-06 17:00:00"12}13function detectWeb (doc, url) {14 15 if (doc.title.match("Liste détaillée des fonds")) {16 return "multiple";17 } else if (doc.title.match("Description fonds")) {18 return "book";19 }20}21//Bibliotheque et Archives National du Quebec. Code by Adam Crymble22function associateData (newItem, dataTags, field, zoteroField) {23 if (dataTags[field]) {24 newItem[zoteroField] = dataTags[field];25 }26}27function scrape(doc, url) {28 var namespace = doc.documentElement.namespaceURI;29 var nsResolver = namespace ? function(prefix) {30 if (prefix == 'x') return namespace; else return null;31 } : null;32 33 var dataTags = new Object();34 var fieldTitle;35 var tagsContent= new Array();36 var newItem = new Zotero.Item("book");37 38 var headers = doc.evaluate('//strong', doc, nsResolver, XPathResult.ANY_TYPE, null);39 var xPathCount = doc.evaluate('count (//strong)', doc, nsResolver, XPathResult.ANY_TYPE, null);40 var contents = doc.evaluate('//div[@id="Content"]/div/table', doc, nsResolver, XPathResult.ANY_TYPE, null).iterateNext().textContent;41 42 var headersArray = new Array();43 var oneHeader = '';44 if (xPathCount.numberValue > 1) {45 for (var i = 0; i < xPathCount.numberValue; i++) {46 fieldTitle = headers.iterateNext().textContent;47 headersArray.push(fieldTitle);48 }49 } else {50 oneHeader = (headers.iterateNext().textContent);51 }52 53 var contentsArray = new Array();54 var j = 0;55 56 if (oneHeader.length<1) {57 58 for (var i = headersArray.length-1; i> -1; i--) { 59 60 var fieldIndex = contents.indexOf(headersArray[i]);61 var removeHeader = headersArray[i].length;62 63 contentsArray.push(contents.substr(fieldIndex));64 contents = contents.substr(0, fieldIndex);65 fieldTitle = headersArray[i].replace(/\s+/g, '');66 67 dataTags[fieldTitle] = contentsArray[j].substr(removeHeader).replace(/^\s*|\s+$/g, '');68 j++;69 }70 } 71 Zotero.debug(dataTags);72 73 if (dataTags["Titre,Dates,Quantité"]) {74 if (dataTags["Titre,Dates,Quantité"].match(/\n/)) {75 var splitTitle = dataTags["Titre,Dates,Quantité"].split(/\n/);76 if (splitTitle[0].match(/\w/)) {77 newItem.title = splitTitle[0].replace(/^\s*|\s+$/g, '');78 }79 for (var i = 0; i < splitTitle.length; i++) {80 if (splitTitle[i].match("/ ")) {81 var author = splitTitle[i].replace(/^\s*|\s+$/g, '').substr(2);82 newItem.creators.push({lastName: author, creatorType: "creator"});83 }84 }85 }86 } else {87 newItem.title = doc.title;88 }89 90 91 var k = 0;92 if (dataTags["Termesrattachés"]) {93 94 if (dataTags["Termesrattachés"].match(/\n/)) {95 tagsContent = dataTags["Termesrattachés"].split(/\n/);96 for (var i in tagsContent) {97 if (tagsContent[i].match(/\w/)) {98 newItem.tags[k] = tagsContent[i].replace(/^\s+|\s*$/g, ''); 99 k++;100 }101 }102 } else {103 newItem.tags[0] = dataTags["Termesrattachés"];104 } 105 }106 107 associateData (newItem, dataTags, "Languedesdocuments", "language");108 associateData (newItem, dataTags, "Cote:", "callNumber");109 associateData (newItem, dataTags, "Collation", "pages");110 associateData (newItem, dataTags, "Centre:", "place");111 associateData (newItem, dataTags, "Portéeetcontenu", "abstractNote");112 113 newItem.url = doc.location.href;114 newItem.complete(); 115}116function doWeb(doc, url) {117 var namespace = doc.documentElement.namespaceURI;118 var nsResolver = namespace ? function(prefix) {119 if (prefix == 'x') return namespace; else return null;120 } : null;121 122 var articles = new Array();123 124 if (detectWeb(doc, url) == "multiple") {125 var items = new Object();126 127 var titles = doc.evaluate('//td[2]/a', doc, nsResolver, XPathResult.ANY_TYPE, null);128 129 var next_title; 130 while (next_title = titles.iterateNext()) {131 if (next_title.href.match("description_fonds")) {132 items[next_title.href] = next_title.textContent;133 }134 }135 items = Zotero.selectItems(items);136 for (var i in items) {137 articles.push(i);138 }139 } else {140 articles = [url];141 }142 Zotero.Utilities.processDocuments(articles, scrape, function() {Zotero.done();});143 Zotero.wait();...
National Archives of South Africa.js
1{2 "translatorID": "5b02e8d4-d8fb-4143-af3d-3576d4c1b49c",3 "label": "National Archives of South Africa",4 "creator": "Adam Crymble",5 "target": "^https?://www\\.national\\.archsrch\\.gov\\.za",6 "minVersion": "3.0",7 "maxVersion": "",8 "priority": 100,9 "inRepository": true,10 "translatorType": 4,11 "browserSupport": "gcsb",12 "lastUpdated": "2014-03-12 22:00:51"13}14function detectWeb(doc, url) {15 if (doc.title.match("Results Summary")) {16 return "multiple";17 } else if (doc.title.match("Results Detail")) {18 return "book";19 }20}21//National Archives of South Africa Translator. Code by Adam Crymble22function associateData(newItem, dataTags, field, zoteroField) {23 if (dataTags[field]) {24 newItem[zoteroField] = dataTags[field];25 }26}27function scrape(doc, url) {28 var dataTags = new Object();29 var tagsContent = new Array();30 var fieldTitle;31 var newItem = new Zotero.Item("book");32 var headers = doc.evaluate('//td[2]/pre/b', doc, null, XPathResult.ANY_TYPE, null);33 var xPathCount = doc.evaluate('count (//td[2]/pre/b)', doc, null, XPathResult.ANY_TYPE, null);34 var contents = doc.evaluate('//td[2]/pre', doc, null, XPathResult.ANY_TYPE, null).iterateNext().textContent;35 var headersArray = new Array();36 var oneHeader = '';37 if (xPathCount.numberValue > 1) {38 for (var i = 0; i < xPathCount.numberValue; i++) {39 fieldTitle = headers.iterateNext().textContent;40 headersArray.push(fieldTitle);41 }42 } else {43 oneHeader = (headers.iterateNext().textContent);44 }45 var contentsArray = new Array();46 var j = 0;47 if (oneHeader.length < 1) {48 for (var i = headersArray.length - 1; i > -1; i--) {49 var fieldIndex = contents.indexOf(headersArray[i]);50 var shorten = headersArray[i].length;51 contentsArray.push(contents.substr(fieldIndex));52 contents = contents.substr(0, fieldIndex);53 fieldTitle = headersArray[i].replace(/\s+/g, '');54 dataTags[fieldTitle] = contentsArray[j].substr(shorten).replace(/^\s*|\s+$/g, '');55 j++;56 }57 }58 associateData(newItem, dataTags, "DEPOT", "repository");59 associateData(newItem, dataTags, "REFERENCE", "callNumber");60 associateData(newItem, dataTags, "STARTING", "date");61 associateData(newItem, dataTags, "ENDING", "date");62 associateData(newItem, dataTags, "VOLUME_NO", "volume");63 associateData(newItem, dataTags, "REMARKS", "extra");64 associateData(newItem, dataTags, "SUMMARY", "abstractNote");65 associateData(newItem, dataTags, "SOURCE", "series");66 if (dataTags["DESCRIPTION"]) {67 associateData(newItem, dataTags, "DESCRIPTION", "title");68 newItem.title = ZU.capitalizeTitle(newItem.title, ignorePreference = "true")69 } else {70 newItem.title = "No Title Found";71 }72 newItem.complete();73}74function doWeb(doc, url) {75 var articles = new Array();76 if (detectWeb(doc, url) == "multiple") {77 var items = new Object();78 var titles = doc.evaluate('//td/a', doc, null, XPathResult.ANY_TYPE, null);79 var lastLink;80 var next_title;81 while (next_title = titles.iterateNext()) {82 if (!next_title.textContent.match(/^\d\d\d\d/) && !next_title.textContent.match(/\\/) && next_title.textContent.length > 3 && next_title.textContent.match(/\w/)) {83 Zotero.debug(next_title.textContent);84 items[next_title.href] = next_title.textContent.trim();85 }86 }87 Zotero.selectItems(items, function (items) {88 if (!items) {89 return true;90 }91 for (var i in items) {92 articles.push(i);93 }94 ZU.processDocuments(articles, scrape)95 }); 96 }97 else {98 scrape(doc, url);99 }100} 101/** BEGIN TEST CASES **/102var testCases = []...
csv-json.js
Source: csv-json.js
1function transformForDelimiter(valuesArray, delimiter) {2 if (valuesArray instanceof Array) {3 return valuesArray.map((element) => {4 return element.split(delimiter).join(',')5 })6 }7}8function getHeaderRow(valuesArray, { headers, delimiter = ',' }, counter) {9 // operate here on valuess10 let headersArray = []11 if (valuesArray instanceof Array) {12 if (counter === 1) {13 // this chunks have headers row14 if (headers === true) {15 headersArray = valuesArray[0].split(delimiter)16 }17 else {18 headersArray = headers19 // Todo: - check length of new headers = old headers20 }21 }22 return headersArray23 }24}25function transformForHeader(valuesArray, headersArray, counter) {26 if (counter === 1) {27 // remove header row28 valuesArray.shift()29 }30 return valuesArray.reduce((arr, element) => {31 const splittedValues = element.split(',')32 const rowObj = splittedValues.reduce((obj, value, i) => {33 const keyName = headersArray[i];34 const objProp = {}35 objProp[keyName] = value36 return { ...obj, ...objProp }37 }, {})38 return [...arr, rowObj]39 }, [])40}41function transformForSkipComments(valuesArray, commentChar) {42 if (valuesArray instanceof Array) {43 return valuesArray.filter((element) => {44 const len = element.length45 return !(element[0] === commentChar || element[len - 1] === commentChar)46 })47 }48}49function transformation(values, config, counter) {50 const { delimiter = ',', skipComments = false, headersArray = [] } = config51 let valuesArray = values;52 // check for delimiter53 valuesArray = delimiter === ',' ? valuesArray : transformForDelimiter(valuesArray, delimiter)54 // check for skip Comments55 valuesArray = skipComments === false ? valuesArray : transformForSkipComments(valuesArray, '#')56 if (headersArray.length) {57 // iterated and make object 58 valuesArray = transformForHeader(valuesArray, headersArray, counter)59 }60 return valuesArray61}62// generates lines from a csv stream 63async function* csvLines(chunkStream) {64 try {65 let remainingLine = ''; // chunk may ends in the middle of a line66 for await (const chunk of chunkStream) {67 const linesFromChunk = (remainingLine + chunk).split('\n');68 remainingLine = linesFromChunk.pop();69 yield linesFromChunk;70 }71 yield remainingLine;72 } catch (error) {73 throw error74 }75}76// parser 77async function* csvToJsonParser(source, config) {78 try {79 const { headers = false } = config80 let counter = 0;81 for await (let values of csvLines(source)) {82 ++counter // to check if first record is in chunk83 // check for headers84 const headersArray = headers === false ? [] : getHeaderRow(values, config, counter)85 yield transformation(values, { ...config, headersArray }, counter)86 }87 } catch (error) {88 throw error89 }90}91module.exports = {92 csvToJsonParser...
csv-json.mjs
Source: csv-json.mjs
1function transformForDelimiter(valuesArray, delimiter) {2 if (valuesArray instanceof Array) {3 return valuesArray.map((element) => {4 return element.split(delimiter).join(',')5 })6 }7}8function getHeaderRow(valuesArray, { headers, delimiter = ',' }, counter) {9 // operate here on valuess10 let headersArray = []11 if (valuesArray instanceof Array) {12 if (counter === 1) {13 // this chunks have headers row14 if (headers === true) {15 headersArray = valuesArray[0].split(delimiter)16 }17 else {18 headersArray = headers19 // Todo: - check length of new headers = old headers20 }21 }22 return headersArray23 }24}25function transformForHeader(valuesArray, headersArray, counter) {26 if (counter === 1) {27 // remove header row28 valuesArray.shift()29 }30 return valuesArray.reduce((arr, element) => {31 const splittedValues = element.split(',')32 const rowObj = splittedValues.reduce((obj, value, i) => {33 const keyName = headersArray[i];34 const objProp = {}35 objProp[keyName] = value36 return { ...obj, ...objProp }37 }, {})38 return [...arr, rowObj]39 }, [])40}41function transformForSkipComments(valuesArray, commentChar) {42 if (valuesArray instanceof Array) {43 return valuesArray.filter((element) => {44 const len = element.length45 return !(element[0] === commentChar || element[len - 1] === commentChar)46 })47 }48}49function transformation(values, config, counter) {50 const { delimiter = ',', skipComments = false, headersArray = [] } = config51 let valuesArray = values;52 // check for delimiter53 valuesArray = delimiter === ',' ? valuesArray : transformForDelimiter(valuesArray, delimiter)54 // check for skip Comments55 valuesArray = skipComments === false ? valuesArray : transformForSkipComments(valuesArray, '#')56 if (headersArray.length) {57 // iterated and make object 58 valuesArray = transformForHeader(valuesArray, headersArray, counter)59 }60 return valuesArray61}62// generates lines from a csv stream 63async function* csvLines(chunkStream) {64 try {65 let remainingLine = ''; // chunk may ends in the middle of a line66 for await (const chunk of chunkStream) {67 const linesFromChunk = (remainingLine + chunk).split('\n');68 remainingLine = linesFromChunk.pop();69 yield linesFromChunk;70 }71 yield remainingLine;72 } catch (error) {73 throw error74 }75}76// parser 77export async function* csvToJsonParser(source, config) {78 try {79 const { headers = false } = config80 let counter = 0;81 for await (let values of csvLines(source)) {82 ++counter // to check if first record is in chunk83 // check for headers84 const headersArray = headers === false ? [] : getHeaderRow(values, config, counter)85 yield transformation(values, { ...config, headersArray }, counter)86 }87 } catch (error) {88 throw error89 }...
NWayMap.js
Source: NWayMap.js
1function NWayMap(input, headersArray) {2 this.isNWayMap = true;3 if (input.isNWayMap) {4 this.headersArray = input.headersArray;5 this.dataByHeaders = input.dataByHeaders;6 return this;7 }8 this.headersArray = headersArray;9 this.dataByHeaders = {};10 var objArr;11 if (this.type(input) === "object") {12 objArr = _.values(input);13 } else if (this.type(input) === "array") {14 objArr = input;15 }16 for (var i = 0; i < headersArray.length; i++) {17 var header = headersArray[i];18 this.dataByHeaders[header] = {};19 }20 for (var i = 0; i < objArr.length; i++) {21 this.put(objArr[i]);22 }23 return this;24}25NWayMap.prototype.checkHeader = function(header) {26 if (!_.contains(this.headersArray, header)) {27 throw "Error: Invalid header: " + header;28 }29};30NWayMap.prototype.put = function(value) {31 for (var i = 0; i < this.headersArray.length; i++) {32 var header = this.headersArray[i];33 if (this.get(header, value[header]) !== null) {34 throw "Error: Duplicate entry found in header: " + header + " for value " + JSON.stringify(value);35 }36 }37 for (var i = 0; i < this.headersArray.length; i++) {38 var header = this.headersArray[i];39 if (typeof value[header] !== 'undefined' && value[header] !== null) {40 this.dataByHeaders[header][value[header]] = value;41 }42 }43};44NWayMap.prototype.get = function(header, key) {45 this.checkHeader(header);46 return (typeof this.dataByHeaders[header][key] === 'undefined' || this.dataByHeaders[header][key] === null) ? null : this.dataByHeaders[header][key];47};48NWayMap.prototype.remove = function(header, key) {49 var prevValue = this.get(header, key);50 if (prevValue === null) {51 return null;52 }53 for (var i = 0; i < this.headersArray.length; i++) {54 var thisHeader = this.headersArray[i];55 delete this.dataByHeaders[thisHeader][prevValue[thisHeader]];56 }57 return prevValue;58};59NWayMap.prototype.getKeys = function(header) {60 this.checkHeader(header);61 return Object.keys(this.dataByHeaders[header]);62};63NWayMap.prototype.getValues = function(header) {64 this.checkHeader(header);65 var results = [];66 for (var i = 0; i < Object.keys(this.dataByHeaders[header]).length; i++) {67 results.push(this.dataByHeaders[header][Object.keys(this.dataByHeaders[header])[i]]);68 }69 return results;70};71NWayMap.prototype.type = function(a) {72 var t = typeof a;73 if (t === "number" && isNaN(a)) {74 return "NaN";75 } else if (t === "object") {76 return toString.call(a).replace("[object ", "").replace("]", "").toLowerCase();77 } else {78 return t.toLowerCase();79 }
...
requester.js
Source: requester.js
1class Requester {2 /**3 * @desc Metodo nativo de React.js4 *5 * @doc https://reactjs.org/docs/react-component.html#constructor6 * @return { void }7 */8 constructor() {9 this.headersArray = new Headers();10 // Cabeceras11 this.headersArray.append('Accept', 'application/json');12 this.headersArray.append('Content-Type', 'application/json');13 this.dispatch = false;14 }15 /**16 * metodo para obtener el dispatch y despachar acciones17 * @return { void }18 */19 addDispatch = (dispatch) => {20 this.dispatch = dispatch;21 };22 /**23 * @desc Añade cabeceras a la request24 *25 * @param { Object } headersArray26 *27 * @return { Headers }28 */29 addHeaders(newHeaders = {}) {30 //31 let {headersArray} = this;32 // Recorremos y añadimos las cabeceras.33 Object.keys(headersArray).length > 0 &&34 headersArray.forEach((prop, value) => {35 headersArray.append(prop, value);36 });37 }38 /**39 * @desc40 *41 * @param { String } endpoint42 *43 * @return { Promise }44 */45 get(endpoint, responseType = 'json') {46 return new Promise((resolve, reject) => {47 /**48 * @desc49 */50 try {51 // Cabeceras.52 let headers = this.headersArray;53 // Armamos el requester54 let request = new Request(endpoint, {55 method: 'GET',56 headers,57 cache: 'default',58 });59 let responseHeader = null;60 //61 fetch(request)62 .then((result) => {63 responseHeader = result.headers;64 if (result.status !== 200) {65 reject(result);66 return result;67 }68 return result[responseType]();69 })70 .then((response) => {71 response.headers = responseHeader;72 resolve(response);73 })74 .catch(reject);75 } catch (e) {76 reject(e.stack);77 }78 });79 }80 /**81 * Metodo para hacer request post82 * @param { String } endpoint83 * @param { Object } data84 * @return { Promise }85 */86 async post(endpoint, data) {87 try {88 // Cabeceras.89 let headers = this.headersArray;90 // Instancia del request.91 let request = new Request(endpoint, {92 method: 'POST',93 headers,94 body: JSON.stringify(data),95 cache: 'default',96 });97 // Solicitud98 const response = await fetch(request);99 // Parseamos a json.100 const result = await response.json();101 // Asignamos la cabecera.102 result.headers = response.headers;103 result.statusCode = response.status;104 return result;105 } catch (err) {106 return {107 error: {108 message: 'No se pudo conectar con el servidor',109 body: err,110 },111 };112 }113 }114}...
cf_elf_JSHeaderRequest.js
Source: cf_elf_JSHeaderRequest.js
1// 2. Extract Headers2var headerFieldsCollection = context.getVariable('request.headers.names') + '';3//Remove square brackets4headerFieldsCollection = headerFieldsCollection.substr(1, headerFieldsCollection.length - 2);5//Split string into an array6var headersArray = headerFieldsCollection.split(", ");7// get and create app attributes in case client uses basic auth8var authorization = context.getVariable("authorization");9var elfRequestHeaders = '{';10// Loop through Array and get value of header11for (var i = 0; i < headersArray.length; i++) {12 context.setVariable('headers.' + headersArray[i].toLowerCase(), context.getVariable('request.header.' + headersArray[i]));13 if(headersArray[i].toLowerCase()!=='authorization'){14 if (i!==0)15 elfRequestHeaders = elfRequestHeaders+',';16 elfRequestHeaders = elfRequestHeaders+'"request.header.' +headersArray[i]+'":"'+context.getVariable('request.header.' + headersArray[i])+'"';17 }18 // Below values assigned to have minimal impact to existing code19 context.setVariable(headersArray[i].toLowerCase(), context.getVariable('request.header.' + headersArray[i]));20}21elfRequestHeaders = elfRequestHeaders+"}";22context.setVariable("elfRequestHeaders",elfRequestHeaders);23// Store data required for logging24context.setVariable("elfLog.interactionId", context.getVariable("interactionid"));25context.setVariable("elfLog.workflowId", context.getVariable("workflowid"));26context.setVariable("elfLog.activityId", context.getVariable("activityid"));27context.setVariable("elfLog.requestVerb", context.getVariable("request.verb"));28context.setVariable("elfLog.proxyRequest", context.getVariable("request.content"));29context.setVariable("elfLog.contentType", context.getVariable("request.header.Content-Type"));30context.setVariable("elfLog.acceptType", context.getVariable("request.header.Accept"));31//context.setVariable("requestHeaderHost", context.getVariable("request.header.host"));32context.setVariable("requestHeaderHost", context.getVariable("hostName"));33context.setVariable("serviceTransactionId", context.getVariable("request.header.serviceTransactionId"));34context.setVariable("messageid", context.getVariable("request.header.messageid"));35context.setVariable("elfLog.logPayloadScope", context.getVariable("app.elfLog.logPayloadScope"));36// Variables to store all target requests and responses in a flow. These are stored in the order they are executed. Finally, these are used during ELF/Splunk logging37/*var targetRequestIndex = 0;...
Using AI Code Generation
1const { headersArray } = require('@playwright/test/lib/utils/utils');2const { chromium } = require('playwright');3(async () => {4 const browser = await chromium.launch();5 const context = await browser.newContext();6 const page = await context.newPage();7 const headers = await page.evaluate(headersArray, page._delegate._requestHeaders);8 console.log(headers);9 await browser.close();10})();
Using AI Code Generation
1const { headersArray } = require('playwright/lib/utils/utils');2const headers = headersArray({ 'Content-Type': 'application/json' });3console.log(headers);4const { headersObject } = require('playwright/lib/utils/utils');5const headers = headersObject([['Content-Type', 'application/json']]);6console.log(headers);7const { headersArray } = require('playwright/lib/utils/utils');8const { headersObject } = require('playwright/lib/utils/utils');9const headers = headersObject(headersArray({ 'Content-Type': 'application/json' }));10console.log(headers);
Using AI Code Generation
1const { headersArray } = require('playwright/lib/utils/utils');2const headers = headersArray([3]);4console.log(headers);5const { chromium } = require('playwright-chromium');6const { addHeaders } = require('playwright-headers');7(async () => {8 const browser = await chromium.launch();9 const context = await browser.newContext();10 const page = await context.newPage();11 await addHeaders(context, [12 ]);13})();14### addHeaders(context, headers)15MIT © [Rafael Goulart](
Using AI Code Generation
1const { headersArray } = require('playwright/lib/utils/utils');2const headers = headersArray(['Content-Type', 'application/json']);3console.log(headers);4const { headersObject } = require('playwright/lib/utils/utils');5const headers = headersObject(['Content-Type', 'application/json']);6console.log(headers);7const { headersObject } = require('playwright/lib/utils/utils');8const headers = headersObject({ 'Content-Type': 'application/json' });9console.log(headers);10const { mergeHeaders } = require('playwright/lib/utils/utils');11const headers = mergeHeaders({ 'Content-Type': 'application/json' }, { 'Content-Type': 'application/json' });12console.log(headers);13const { isSafeCloseError } = require('playwright/lib/utils/utils');14const headers = isSafeCloseError({ 'Content-Type': 'application/json' });15console.log(headers);16const { isSafeCloseError } = require('playwright/lib/utils/utils');17const headers = isSafeCloseError({ 'message': 'Target closed.' });18console.log(headers);19const { isSafeCloseError } = require('playwright/lib/utils/utils');20const headers = isSafeCloseError({ 'message': 'Target closed.' });21console.log(headers);22const { isSafeCloseError } = require('playwright/lib/utils/utils');23const headers = isSafeCloseError({ 'message': 'Target closed.' });24console.log(headers);25const { isSafeCloseError } = require('playwright/lib/utils/utils');26const headers = isSafeCloseError({ 'message': 'Target closed.' });27console.log(headers
firefox browser does not start in playwright
Running Playwright in Azure Function
firefox browser does not start in playwright
Is it possible to get the selector from a locator object in playwright?
Jest + Playwright - Test callbacks of event-based DOM library
How to run a list of test suites in a single file concurrently in jest?
I found the error. It was because of some missing libraries need. I discovered this when I downgraded playwright to version 1.9 and ran the the code then this was the error msg:
(node:12876) UnhandledPromiseRejectionWarning: browserType.launch: Host system is missing dependencies!
Some of the Universal C Runtime files cannot be found on the system. You can fix
that by installing Microsoft Visual C++ Redistributable for Visual Studio from:
https://support.microsoft.com/en-us/help/2977003/the-latest-supported-visual-c-downloads
Full list of missing libraries:
vcruntime140.dll
msvcp140.dll
Error
at Object.captureStackTrace (D:\Projects\snkrs-play\node_modules\playwright\lib\utils\stackTrace.js:48:19)
at Connection.sendMessageToServer (D:\Projects\snkrs-play\node_modules\playwright\lib\client\connection.js:69:48)
at Proxy.<anonymous> (D:\Projects\snkrs-play\node_modules\playwright\lib\client\channelOwner.js:64:61)
at D:\Projects\snkrs-play\node_modules\playwright\lib\client\browserType.js:64:67
at BrowserType._wrapApiCall (D:\Projects\snkrs-play\node_modules\playwright\lib\client\channelOwner.js:77:34)
at BrowserType.launch (D:\Projects\snkrs-play\node_modules\playwright\lib\client\browserType.js:55:21)
at D:\Projects\snkrs-play\index.js:4:35
at Object.<anonymous> (D:\Projects\snkrs-play\index.js:7:3)
at Module._compile (internal/modules/cjs/loader.js:1063:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:12876) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:12876) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
A list of missing libraries was provided. After successful installments, firefox ran fine. I upgraded again to version 1.10 and firefox still works.
Check out the latest blogs from LambdaTest on this topic:
Building a website is all about keeping the user experience in mind. Ultimately, it’s about providing visitors with a mind-blowing experience so they’ll keep coming back. One way to ensure visitors have a great time on your site is to add some eye-catching text or image animations.
In my last blog, I investigated both the stateless and the stateful class of model-based testing. Both have some advantages and disadvantages. You can use them for different types of systems, depending on whether a stateful solution is required or a stateless one is enough. However, a better solution is to use an aggregate technique that is appropriate for each system. Currently, the only aggregate solution is action-state testing, introduced in the book Paradigm Shift in Software Testing. This method is implemented in Harmony.
The holidays are just around the corner, and with Christmas and New Year celebrations coming up, everyone is busy preparing for the festivities! And during this busy time of year, LambdaTest also prepped something special for our beloved developers and testers – #LambdaTestYourBusiness
Xamarin is an open-source framework that offers cross-platform application development using the C# programming language. It helps to simplify your overall development and management of cross-platform software applications.
With the change in technology trends, there has been a drastic change in the way we build and develop applications. It is essential to simplify your programming requirements to achieve the desired outcomes in the long run. Visual Studio Code is regarded as one of the best IDEs for web development used by developers.
LambdaTest’s Playwright tutorial will give you a broader idea about the Playwright automation framework, its unique features, and use cases with examples to exceed your understanding of Playwright testing. This tutorial will give A to Z guidance, from installing the Playwright framework to some best practices and advanced concepts.
Get 100 minutes of automation test minutes FREE!!