How to use respond method in Puppeteer

Best JavaScript code snippet using puppeteer

fake_server_test.js

Source:fake_server_test.js Github

copy

Full Screen

...123 this.server.restore();124 },125 "should respond to queued async requests": function () {126 this.server.respondWith("Oh yeah! Duffman!");127 this.server.respond();128 assert(this.getRootAsync.respond.called);129 assertEquals([200, {}, "Oh yeah! Duffman!"], this.getRootAsync.respond.args[0]);130 },131 "should respond to all queued async requests": function () {132 this.server.respondWith("Oh yeah! Duffman!");133 this.server.respond();134 assert(this.getRootAsync.respond.called);135 assert(this.getPathAsync.respond.called);136 },137 "should respond with status, headers, and body": function () {138 var headers = { "Content-Type": "X-test" };139 this.server.respondWith([201, headers, "Oh yeah!"]);140 this.server.respond();141 assertEquals([201, headers, "Oh yeah!"], this.getRootAsync.respond.args[0]);142 },143 "should handle responding with empty queue": function () {144 delete this.server.queue;145 var server = this.server;146 assertNoException(function () {147 server.respond();148 });149 },150 "should respond to sync request with canned answers": function () {151 this.server.respondWith([210, { "X-Ops": "Yeah" }, "Body, man"]);152 this.getRootSync.send();153 assertEquals(210, this.getRootSync.status);154 assertEquals({ "x-ops": "Yeah" }, this.getRootSync.getAllResponseHeaders());155 assertEquals("Body, man", this.getRootSync.responseText);156 },157 "should respond to sync request with 404 if no response is set": function () {158 this.getRootSync.send();159 assertEquals(404, this.getRootSync.status);160 assertEquals({}, this.getRootSync.getAllResponseHeaders());161 assertEquals("", this.getRootSync.responseText);162 },163 "should respond to async request with 404 if no response is set": function () {164 this.server.respond();165 assertEquals([404, {}, ""], this.getRootAsync.respond.args[0]);166 },167 "should respond to specific URL": function () {168 this.server.respondWith("/path", "Duffman likes Duff beer");169 this.server.respond();170 assertEquals([404, {}, ""], this.getRootAsync.respond.args[0]);171 assertEquals([200, {}, "Duffman likes Duff beer"], this.getPathAsync.respond.args[0]);172 },173 "should respond to URL matched by regexp": function () {174 this.server.respondWith(/^\/p.*/, "Regexp");175 this.server.respond();176 assertEquals([200, {}, "Regexp"], this.getPathAsync.respond.args[0]);177 },178 "should not respond to URL not matched by regexp": function () {179 this.server.respondWith(/^\/p.*/, "No regexp match");180 this.server.respond();181 assertEquals([404, {}, ""], this.getRootAsync.respond.args[0]);182 },183 "should respond to all URLs matched by regexp": function () {184 this.server.respondWith(/^\/.*/, "Match all URLs");185 this.server.respond();186 assertEquals([200, {}, "Match all URLs"], this.getRootAsync.respond.args[0]);187 assertEquals([200, {}, "Match all URLs"], this.getPathAsync.respond.args[0]);188 },189 "should respond to all requests when match URL is falsy": function () {190 this.server.respondWith("", "Falsy URL");191 this.server.respond();192 assertEquals([200, {}, "Falsy URL"], this.getRootAsync.respond.args[0]);193 assertEquals([200, {}, "Falsy URL"], this.getPathAsync.respond.args[0]);194 },195 "should respond to all GET requests": function () {196 this.server.respondWith("GET", "", "All GETs");197 this.server.respond();198 assertEquals([200, {}, "All GETs"], this.getRootAsync.respond.args[0]);199 assertEquals([200, {}, "All GETs"], this.getPathAsync.respond.args[0]);200 assertEquals([404, {}, ""], this.postRootAsync.respond.args[0]);201 assertEquals([404, {}, ""], this.postPathAsync.respond.args[0]);202 },203 "should respond to all 'get' requests (case-insensitivity)": function () {204 this.server.respondWith("get", "", "All GETs");205 this.server.respond();206 assertEquals([200, {}, "All GETs"], this.getRootAsync.respond.args[0]);207 assertEquals([200, {}, "All GETs"], this.getPathAsync.respond.args[0]);208 assertEquals([404, {}, ""], this.postRootAsync.respond.args[0]);209 assertEquals([404, {}, ""], this.postPathAsync.respond.args[0]);210 },211 "should respond to all PUT requests": function () {212 this.server.respondWith("PUT", "", "All PUTs");213 this.server.respond();214 assertEquals([404, {}, ""], this.getRootAsync.respond.args[0]);215 assertEquals([404, {}, ""], this.getPathAsync.respond.args[0]);216 assertEquals([404, {}, ""], this.postRootAsync.respond.args[0]);217 assertEquals([404, {}, ""], this.postPathAsync.respond.args[0]);218 },219 "should respond to all POST requests": function () {220 this.server.respondWith("POST", "", "All POSTs");221 this.server.respond();222 assertEquals([404, {}, ""], this.getRootAsync.respond.args[0]);223 assertEquals([404, {}, ""], this.getPathAsync.respond.args[0]);224 assertEquals([200, {}, "All POSTs"], this.postRootAsync.respond.args[0]);225 assertEquals([200, {}, "All POSTs"], this.postPathAsync.respond.args[0]);226 },227 "should respond to all POST requests to /path": function () {228 this.server.respondWith("POST", "/path", "All POSTs");229 this.server.respond();230 assertEquals([404, {}, ""], this.getRootAsync.respond.args[0]);231 assertEquals([404, {}, ""], this.getPathAsync.respond.args[0]);232 assertEquals([404, {}, ""], this.postRootAsync.respond.args[0]);233 assertEquals([200, {}, "All POSTs"], this.postPathAsync.respond.args[0]);234 },235 "should respond to all POST requests matching regexp": function () {236 this.server.respondWith("POST", /^\/path(\?.*)?/, "All POSTs");237 this.server.respond();238 assertEquals([404, {}, ""], this.getRootAsync.respond.args[0]);239 assertEquals([404, {}, ""], this.getPathAsync.respond.args[0]);240 assertEquals([404, {}, ""], this.postRootAsync.respond.args[0]);241 assertEquals([200, {}, "All POSTs"], this.postPathAsync.respond.args[0]);242 },243 "should not respond to aborted requests": function () {244 this.server.respondWith("/", "That's my homepage!");245 this.getRootAsync.aborted = true;246 this.server.respond();247 assertFalse(this.getRootAsync.respond.called);248 },249 "should reset requests": function () {250 this.server.respondWith("/", "That's my homepage!");251 this.server.respond();252 assertEquals([], this.server.queue);253 },254 "should notify all requests when some throw": function () {255 this.getRootAsync.respond = function () {256 throw new Error("Oops!");257 };258 this.server.respondWith("");259 this.server.respond();260 assertEquals([200, {}, ""], this.getPathAsync.respond.args[0]);261 assertEquals([200, {}, ""], this.postRootAsync.respond.args[0]);262 assertEquals([200, {}, ""], this.postPathAsync.respond.args[0]);263 }264});265testCase("ServerRespondFakeHTTPVerbTest", {266 setUp: function () {267 this.server = sinon.fakeServer.create();268 this.request = new sinon.FakeXMLHttpRequest();269 this.request.open("post", "/path", true);270 this.request.send("_method=delete");271 sinon.spy(this.request, "respond");272 },273 tearDown: function () {274 this.server.restore();275 },276 "should not respond to DELETE request with _method parameter": function () {277 this.server.respondWith("DELETE", "", "");278 this.server.respond();279 assertEquals([404, {}, ""], this.request.respond.args[0]);280 },281 "should respond to 'fake' DELETE request": function () {282 this.server.fakeHTTPMethods = true;283 this.server.respondWith("DELETE", "", "OK");284 this.server.respond();285 assertEquals([200, {}, "OK"], this.request.respond.args[0]);286 },287 "should not respond to POST when faking DELETE": function () {288 this.server.fakeHTTPMethods = true;289 this.server.respondWith("POST", "", "OK");290 this.server.respond();291 assertEquals([404, {}, ""], this.request.respond.args[0]);292 },293 "should not fake method when not POSTing": function () {294 this.server.fakeHTTPMethods = true;295 this.server.respondWith("DELETE", "", "OK");296 var request = new sinon.FakeXMLHttpRequest();297 request.open("GET", "/");298 request.send();299 request.respond = sinon.spy();300 this.server.respond();301 assertEquals([404, {}, ""], request.respond.args[0]);302 },303 "should customize HTTP method extraction": function () {304 this.server.getHTTPMethod = function (request) {305 return "PUT";306 };307 this.server.respondWith("PUT", "", "OK");308 this.server.respond();309 assertEquals([200, {}, "OK"], this.request.respond.args[0]);310 }...

Full Screen

Full Screen

wrappedElement.js

Source:wrappedElement.js Github

copy

Full Screen

1// Licensed to the Software Freedom Conservancy (SFC) under one2// or more contributor license agreements. See the NOTICE file3// distributed with this work for additional information4// regarding copyright ownership. The SFC licenses this file5// to you under the Apache License, Version 2.0 (the6// "License"); you may not use this file except in compliance7// with the License. You may obtain a copy of the License at8//9// http://www.apache.org/licenses/LICENSE-2.010//11// Unless required by applicable law or agreed to in writing,12// software distributed under the License is distributed on an13// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY14// KIND, either express or implied. See the License for the15// specific language governing permissions and limitations16// under the License.17goog.provide('WebElement');18goog.require('Utils');19goog.require('WebLoadingListener');20goog.require('bot.ErrorCode');21goog.require('bot.action');22goog.require('bot.dom');23goog.require('fxdriver.io');24goog.require('fxdriver.logging');25goog.require('fxdriver.moz');26goog.require('fxdriver.preconditions');27goog.require('goog.dom');28goog.require('goog.dom.TagName');29goog.require('goog.dom.selection');30goog.require('goog.log');31goog.require('goog.math.Coordinate');32goog.require('webdriver.atoms.element');33/**34 * @private {goog.log.Logger}35 * @const36 */37WebElement.LOG_ = fxdriver.logging.getLogger('fxdriver.WebElement');38WebElement.elementEquals = function(respond, parameters) {39 try {40 var elementA = Utils.getElementAt(parameters.id,41 respond.session.getDocument());42 var elementB = Utils.getElementAt(parameters.other,43 respond.session.getDocument());44 respond.value = elementA == elementB;45 } catch (e) {46 if (e.code && e.code == bot.ErrorCode.STALE_ELEMENT_REFERENCE) {47 // Assume any style elements are not equal to any others.48 // Users shouldn't care about equality of stale elements.49 respond.value = false;50 } else {51 throw e;52 }53 }54 respond.send();55};56WebElement.clickElement = function(respond, parameters) {57 var element = Utils.getElementAt(parameters.id,58 respond.session.getDocument());59 // Handle the special case of the file input element here60 if (bot.dom.isElement(element, goog.dom.TagName.INPUT)) {61 var inputtype = element.getAttribute('type');62 if (inputtype && inputtype.toLowerCase() == 'file') {63 respond.status = bot.ErrorCode.INVALID_ARGUMENT;64 respond.send();65 return;66 }67 }68 var unwrapped = fxdriver.moz.unwrapFor4(element);69 var offset = Utils.getClickablePoint(unwrapped);70 var inViewAfterScroll = Utils.scrollIntoView(71 unwrapped,72 (respond.session.elementScrollBehavior == 0),73 new goog.math.Coordinate(offset.x, offset.y));74 Utils.installWindowCloseListener(respond);75 Utils.installClickListener(respond, WebLoadingListener);76 var res = this.mouse.move(element, offset.x, offset.y);77 if (res.status != bot.ErrorCode.SUCCESS) {78 respond.status = res.status;79 respond.value = res.message;80 respond.send();81 return;82 }83 res = this.mouse.click(element);84 respond.status = res.status;85 respond.value = res.message;86};87WebElement.clickElement.preconditions =88 [fxdriver.preconditions.visible];89WebElement.getElementText = function(respond, parameters) {90 var element = Utils.getElementAt(parameters.id,91 respond.session.getDocument());92 respond.value = webdriver.atoms.element.getText(element);93 respond.send();94};95WebElement.sendKeysToElement = function(respond, parameters) {96 var element = Utils.getElementAt(parameters.id,97 respond.session.getDocument());98 var browser = respond.session.getBrowser();99 var dispatcher = browser.ownerDocument.commandDispatcher;100 var currentDocument =101 dispatcher.focusedElement && goog.dom.getOwnerDocument(dispatcher.focusedElement);102 currentDocument = currentDocument ? new XPCNativeWrapper(currentDocument) : null;103 var alreadyFocused = true;104 var currentlyActive = Utils.getActiveElement(respond.session.getDocument());105 var newDocument = goog.dom.getOwnerDocument(currentlyActive);106 if (currentlyActive != element || currentDocument != new XPCNativeWrapper(newDocument)) {107 goog.log.info(WebElement.LOG_, 'Need to switch focus');108 alreadyFocused = false;109 currentlyActive.blur();110 element.focus();111 element.ownerDocument.defaultView.focus();112 } else {113 goog.log.info(WebElement.LOG_, 'No need to switch focus');114 }115 var use = element;116 var tagName = element.tagName.toLowerCase();117 if (tagName == 'body' && element.ownerDocument.defaultView.frameElement) {118 element.ownerDocument.defaultView.focus();119 // Turns out, this is what we should be using as the target120 // to send events to121 use = element.ownerDocument.getElementsByTagName('html')[0];122 }123 // Handle the special case of the file input element here124 if (bot.dom.isElement(element, goog.dom.TagName.INPUT)) {125 var inputtype = element.getAttribute('type');126 if (inputtype && inputtype.toLowerCase() == 'file') {127 element.value = parameters.value.join('');128 Utils.fireHtmlEvent(element, 'change');129 respond.send();130 return;131 }132 }133 var originalDriver = this;134 // We may need a beat for firefox to hand over focus.135 this.jsTimer.setTimeout(function() {136 if (!alreadyFocused && bot.dom.isEditable(element)) {137 var length = element.value ? element.value.length : goog.dom.getTextContent(element).length;138 if (bot.dom.isContentEditable(element) && length) {139 var setCursorTo = element;140 if (element.lastElementChild) {141 setCursorTo = element.lastElementChild;142 }143 goog.log.info(WebElement.LOG_, 'ContentEditable ' + element + " " + length);144 var doc = element.ownerDocument || element.document;145 var rng = doc.createRange();146 rng.selectNodeContents(setCursorTo);147 rng.collapse(false);148 var sel = doc.getSelection();149 sel.removeAllRanges();150 sel.addRange(rng);151 } else {152 goog.dom.selection.setCursorPosition(element, length);153 }154 }155 try {156 Utils.type(respond.session, use, parameters.value.join(''),157 originalDriver.jsTimer, true /*release modifiers*/);158 respond.send();159 } catch (ex) {160 respond.sendError(ex);161 }162 }, 0);163};164WebElement.sendKeysToElement.preconditions =165 [fxdriver.preconditions.visible, fxdriver.preconditions.enabled];166WebElement.clearElement = function(respond, parameters) {167 var element = Utils.getElementAt(parameters.id,168 respond.session.getDocument());169 bot.setWindow(respond.session.getWindow());170 try {171 bot.action.clear(element);172 respond.send();173 } catch (e) {174 var code = e.code;175 if (code) {176 respond.sendError(new WebDriverError(code, e.message));177 } else {178 throw e;179 }180 }181};182WebElement.clearElement.preconditions =183 [fxdriver.preconditions.visible, fxdriver.preconditions.enabled, fxdriver.preconditions.writable];184WebElement.getElementTagName = function(respond, parameters) {185 var element = Utils.getElementAt(parameters.id,186 respond.session.getDocument());187 respond.value = element.tagName.toLowerCase();188 respond.send();189};190WebElement.getElementAttribute = function(respond, parameters) {191 var element = fxdriver.moz.unwrap(192 Utils.getElementAt(parameters.id, respond.session.getDocument()));193 var attributeName = parameters.name;194 respond.value = webdriver.atoms.element.getAttribute(element, attributeName);195 respond.send();196};197WebElement.isElementEnabled = function(respond, parameters) {198 var element = Utils.getElementAt(parameters.id,199 respond.session.getDocument());200 respond.value = bot.dom.isEnabled(element);201 respond.send();202};203WebElement.submitElement = function(respond, parameters) {204 var element = Utils.getElementAt(parameters.id,205 respond.session.getDocument());206 if (element) {207 while (element.parentNode != null && element.tagName.toLowerCase() != 'form') {208 element = element.parentNode;209 }210 if (element.tagName && element.tagName.toLowerCase() == 'form') {211 var current = respond.session.getWindow().location;212 if (Utils.fireHtmlEvent(element, 'submit') &&213 fxdriver.io.isLoadExpected(current, element.action)) {214 new WebLoadingListener(respond.session.getBrowser(), function(timedOut) {215 if (timedOut) {216 respond.sendError(new WebDriverError(bot.ErrorCode.TIMEOUT,217 'Timed out waiting for page load.'));218 } else {219 respond.send();220 }221 }, respond.session.getPageLoadTimeout(), respond.session.getWindow());222 element.submit();223 return;224 } else {225 //Event was blocked, so don't submit226 respond.send();227 return;228 }229 } else {230 throw new WebDriverError(bot.ErrorCode.NO_SUCH_ELEMENT,231 "Element was not in a form so couldn't submit");232 }233 }234 respond.send();235};236WebElement.isElementSelected = function(respond, parameters) {237 var element = Utils.getElementAt(parameters.id,238 respond.session.getDocument());239 var selected = false;240 try {241 var option =242 element.QueryInterface(Components.interfaces.nsIDOMHTMLOptionElement);243 selected = option.selected;244 } catch (e) {245 }246 try {247 var inputElement =248 element.QueryInterface(Components.interfaces.nsIDOMHTMLInputElement);249 if (inputElement.type == 'checkbox' || inputElement.type == 'radio') {250 selected = inputElement.checked;251 }252 } catch (e) {253 }254 respond.value = selected;255 respond.send();256};257WebElement.isElementDisplayed = function(respond, parameters) {258 var element = Utils.getElementAt(parameters.id,259 respond.session.getDocument());260 respond.value = bot.dom.isShown(element);261 respond.send();262};263WebElement.getElementRect = function(respond, parameters) {264 var element = Utils.getElementAt(parameters.id,265 respond.session.getDocument());266 var win = respond.session.getWindow();267 var rect = Utils.getLocation(element);268 respond.value = {269 x: Math.round(rect.x + win.pageXOffset),270 y: Math.round(rect.y + win.pageYOffset),271 width: Math.round(rect.width),272 height: Math.round(rect.height)273 };274 respond.send();275};276WebElement.getElementValueOfCssProperty = function(respond,277 parameters) {278 var element = Utils.getElementAt(parameters.id,279 respond.session.getDocument());280 respond.value = bot.dom.getEffectiveStyle(element, parameters.propertyName);281 respond.send();282};283WebElement.getElementLocationOnceScrolledIntoView = function(284 respond, parameters) {285 var element = Utils.getElementAt(parameters.id,286 respond.session.getDocument());287 var theDoc = element.ownerDocument;288 Utils.getMainDocumentElement(theDoc).focus();289 var elementLocation = Utils.getLocationOnceScrolledIntoView(290 element, (respond.session.elementScrollBehavior == 0));291 respond.value = {292 x: Math.round(elementLocation.x),293 y: Math.round(elementLocation.y)294 };295 respond.send();...

Full Screen

Full Screen

db-api.js

Source:db-api.js Github

copy

Full Screen

...25}26function addNews (msg, respond) {27 //validation28 if (!msg.data) {29 return respond(new Error('data property is not defined as a parameter'));30 }31 const news = msg.data;32 if (Object.prototype.toString.call(news) !== '[object Array]') {33 return respond(new Error('data parameter should be an array of news'));34 }35 dbConnection.addNews(news)36 .then(status => respond(null, status))37 .catch(err => respond(err));38}39function getNews(msg, respond) {40 //validation41 if (!msg.data) {42 return respond(new Error('data property is not defined as a parameter'));43 }44 const playerId = msg.data;45 if (!playerId)46 return respond(new Error('Please specify the playerId property in the data property of the message'));47 // defer to dbConnection48 dbConnection.getNews(playerId)49 .then(news => respond(null, news))50 .catch(err => respond(err));51}52function getPlayers (msg, respond) {53 dbConnection.getPlayers()54 .then(players => respond(null, players))55 .catch(err => respond(err));56}57function getClubs (msg, respond) {58 dbConnection.getClubs()59 .then(clubs => respond(null, clubs))60 .catch(err => respond(err));61}62function getPlayerValues (msg, respond) {63 if(!msg.data)64 return respond(new Error('data property must be defined and it should contain the playerId'));65 var playerId = msg.data.playerId;66 if (!playerId)67 return respond(new Error('Please specify the playerId property in the data property of the message'));68 var noOfDays = msg.data.noOfDays;69 if (!noOfDays)70 return respond(new Error('Please specify the noOfDays property in the data property of the message'));71 dbConnection.getPlayerValues(playerId, noOfDays)72 .then(playerValues => respond(null, playerValues))73 .catch(err => respond(err));74}75function getAllPlayerValues (msg, respond) {76 dbConnection.getAllPlayerValues()77 .then(playerValues => respond(null, playerValues))78 .catch(err => respond(err));79}80/**81 * Api function to add player values82 * @param {Object} msg.data83 * @param {number} msg.data.playerId84 * @param {Array.<Object>} msg.data.values85 * @param respond86 * @returns {*}87 */88function addPlayerValues (msg, respond) {89 const dbPromises = [];90 if(!msg.data)91 return respond(new Error('data property must be defined and it should contain the playerId and a values array containing {date: date, value: value} objects'));92 const playerId = msg.data.playerId;93 if (!playerId)94 return respond(new Error('Please specify the playerId property in the data property of the message'));95 const values = msg.data.values;96 if (!values) {97 return respond(new Error('The value property of data should be an array containing {quote: Integer, valdate: Date} objects'));98 }99 try {100 const keysCorrect = values.reduce((previous, next) => {101 return previous && next.quote != undefined && next.valdate != undefined;102 }, true);103 if(!keysCorrect) {104 return respond(new Error('The value property of data should be an array containing {quote: Integer, valdate: Date} objects'));105 }106 } catch(err) {107 return respond(new Error('The value property of data should be an array containing {quote: Integer, valdate: Date} objects'));108 }109 dbConnection.addPlayerValues(playerId, values)110 .then(status => respond(null, status))111 .catch(err =>112 respond(err));113}114function lookUpPlayerId (msg, respond) {115 if(!msg.data)116 return respond(new Error('data property must be defined and it should contain the comPlayerId'));117 const comPlayerId = msg.data.comPlayerId;118 if (!comPlayerId)119 return respond(new Error('Please specify the comPlayerId property in the data property of the message'));120 dbConnection.lookUpPlayerId(comPlayerId)121 .then(playerId => respond(null, playerId))122 .catch(err => respond(err));123}124function getPlayerStats (msg, respond) {125 if(!msg.data) return respond(new Error('data property must be defined and it should contain the comPlayerId'));126 const playerId = msg.data.playerId;127 const gameDay = msg.data.gameDay;128 const seasonStart = msg.data.seasonStart;129 if (!playerId || typeof playerId !== "number") return respond(new Error('Parameter playerId is not specified or is not a number'));130 dbConnection.getPlayerStats(playerId, seasonStart, gameDay)131 .then(stats => respond(null, stats))132 .catch(err => respond(err));133}134function addPlayerStats (msg, respond) {135 if(!msg.data) return respond(new Error('data property must be defined and it should contain the comPlayerId'));136 const playerId = msg.data.playerId;137 const gameDay = msg.data.gameDay;138 const seasonStart = msg.data.seasonStart;139 const goals = msg.data.goals;140 const opponentId = msg.data.opponentId;141 const home = msg.data.home;142 const cards = msg.data.cards;143 const subIn = msg.data.subIn;144 const subOut = msg.data.subOut;145 const points = msg.data.points;146 if (playerId == null || typeof playerId !== "number") return respond(new Error('Parameter playerId is not specified or is not a number'));147 if (gameDay ==null || typeof gameDay !== "number") return respond(new Error('Parameter gameDay is not specified or is not a number'));148 if (seasonStart == null || typeof seasonStart !== "number") return respond(new Error('Parameter seasonStart is not specified or is not a number'));149 if (goals == null || typeof goals !== "number") return respond(new Error('Parameter goals is not specified or is not a number'));150 if (!opponentId || typeof opponentId !== "number") return respond(new Error('Parameter opponentId is not specified or is not a number'));151 if (typeof(home) !== "boolean") return respond(new Error('Parameter home is not specified or is not a boolean'));152 if (cards && !(cards === "red" || cards === "yellow" || cards === "yellow-red")) return respond(new Error('Parameter cards must be either yellow, yellow-red or red but is ' + cards));153 if (subIn != null && typeof subIn !== "number") return respond(new Error('Parameter subIn is not a number'));154 if (subOut != null && typeof subOut !== "number") return respond(new Error('Parameter subOut is not a number'));155 if (points != null && typeof points !== "number") return respond(new Error('Parameter points is not a number'));156 dbConnection.addPlayerStats({157 playerId,158 gameDay,159 seasonStart,160 goals,161 opponentId,162 home,163 cards,164 subIn,165 subOut,166 points167 })168 .then(status => respond(undefined, status))169 .catch(err => respond(err));170}171function addAllPlayerStats (msg, respond) {172 if(!msg.data) return respond(new Error('data property must be defined and it should contain the comPlayerId'));173 Promise.all(msg.data.map(playerStat => dbConnection.addPlayerStats(playerStat)))174 .then(status => respond(undefined, status))175 .catch(err => respond(err));176}177function addGame(msg, respond) {178 if(!msg.data) return respond(new Error('data property must be defined and it should contain the comPlayerId'));179 const gameDay = msg.data.gameDay;180 const seasonStart = msg.data.seasonStart;181 const homeScore = msg.data.homeScore;182 const guestScore = msg.data.guestScore;183 const homeClubId = msg.data.homeClubId;184 const guestClubId = msg.data.guestClubId;185 if(checkIfNumber(gameDay)) return respond(noExistenceOrNoNumberRejection("gameDay"));186 if(checkIfNumber(seasonStart)) return respond(noExistenceOrNoNumberRejection("seasonStart"));187 if(checkIfNumber(homeClubId)) return respond(noExistenceOrNoNumberRejection("homeClubId"));188 if(checkIfNumber(guestClubId)) return respond(noExistenceOrNoNumberRejection("guestClubId"));189 if(homeScore && checkIfNumber(homeScore)) return respond(noNumberRejection("homeScore"));190 if(guestScore && checkIfNumber(guestScore)) return respond(noNumberRejection("guestScore"));191 dbConnection.addGame({192 gameDay,193 seasonStart,194 homeScore,195 guestScore,196 homeClubId,197 guestClubId198 })199 .then(status => respond(null, status))200 .catch(err => respond(err));201}202function getGames(msg, respond) {203 if(!msg.data) return respond(new Error('data property must be defined and it should contain the comPlayerId'));204 const seasonStart = msg.data.seasonStart;205 const gameDay = msg.data.gameDay;206 dbConnection.getGames(seasonStart, gameDay)207 .then(games => respond(null, games))208 .catch(err => respond(err));209}210function checkIfNumber(number) {211 return number == null || typeof number !== "number"212}213function noExistenceOrNoNumberRejection(parameter) {214 return new Error('Parameter ' + parameter + ' is not specified or is not a number');215}216function noNumberRejection(parameter) {217 return new Error('Parameter ' + parameter + ' is not a number');...

Full Screen

Full Screen

test_ext_runtime_sendMessage.js

Source:test_ext_runtime_sendMessage.js Github

copy

Full Screen

...4add_task(async function tabsSendMessageReply() {5 function background() {6 browser.runtime.onMessage.addListener((msg, sender, respond) => {7 if (msg == "respond-now") {8 respond(msg);9 } else if (msg == "respond-soon") {10 setTimeout(() => { respond(msg); }, 0);11 return true;12 } else if (msg == "respond-promise") {13 return Promise.resolve(msg);14 } else if (msg == "respond-never") {15 return undefined;16 } else if (msg == "respond-error") {17 return Promise.reject(new Error(msg));18 } else if (msg == "throw-error") {19 throw new Error(msg);20 }21 });22 browser.runtime.onMessage.addListener((msg, sender, respond) => {23 if (msg == "respond-now") {24 respond("hello");25 } else if (msg == "respond-now-2") {26 respond(msg);27 }28 });29 let childFrame = document.createElement("iframe");30 childFrame.src = "extensionpage.html";31 document.body.appendChild(childFrame);32 }33 function senderScript() {34 Promise.all([35 browser.runtime.sendMessage("respond-now"),36 browser.runtime.sendMessage("respond-now-2"),37 new Promise(resolve => browser.runtime.sendMessage("respond-soon", resolve)),38 browser.runtime.sendMessage("respond-promise"),39 browser.runtime.sendMessage("respond-never"),40 new Promise(resolve => {...

Full Screen

Full Screen

plugins.respond.js

Source:plugins.respond.js Github

copy

Full Screen

1/*! jRespond.js v 0.10 | Author: Jeremy Fields [jeremy.fields@viget.com], 2013 | License: MIT */2!function(a,b,c){"object"==typeof module&&module&&"object"==typeof module.exports?module.exports=c:(a[b]=c,"function"==typeof define&&define.amd&&define(b,[],function(){return c}))}(this,"jRespond",function(a,b,c){"use strict";return function(a){var b=[],d=[],e=a,f="",g="",i=0,j=100,k=500,l=k,m=function(){var a=0;return a="number"!=typeof window.innerWidth?0!==document.documentElement.clientWidth?document.documentElement.clientWidth:document.body.clientWidth:window.innerWidth},n=function(a){if(a.length===c)o(a);else for(var b=0;b<a.length;b++)o(a[b])},o=function(a){var e=a.breakpoint,h=a.enter||c;b.push(a),d.push(!1),r(e)&&(h!==c&&h.call(null,{entering:f,exiting:g}),d[b.length-1]=!0)},p=function(){for(var a=[],e=[],h=0;h<b.length;h++){var i=b[h].breakpoint,j=b[h].enter||c,k=b[h].exit||c;"*"===i?(j!==c&&a.push(j),k!==c&&e.push(k)):r(i)?(j===c||d[h]||a.push(j),d[h]=!0):(k!==c&&d[h]&&e.push(k),d[h]=!1)}for(var l={entering:f,exiting:g},m=0;m<e.length;m++)e[m].call(null,l);for(var n=0;n<a.length;n++)a[n].call(null,l)},q=function(a){for(var b=!1,c=0;c<e.length;c++)if(a>=e[c].enter&&a<=e[c].exit){b=!0;break}b&&f!==e[c].label?(g=f,f=e[c].label,p()):b||""===f||(f="",p())},r=function(a){if("object"==typeof a){if(a.join().indexOf(f)>=0)return!0}else{if("*"===a)return!0;if("string"==typeof a&&f===a)return!0}},s=function(){var a=m();a!==i?(l=j,q(a)):l=k,i=a,setTimeout(s,l)};return s(),{addFunc:function(a){n(a)},getBreakpoint:function(){return f}}}}(this,this.document));3SEMICOLON.widget.respondInit = function( $respondEl ){4 $respondEl = $respondEl.filter(':not(.customjs)');5 if( $respondEl.length < 1 ){6 return true;7 }8 let jRes = jRespond([9 {10 label: 'smallest',11 enter: 0,12 exit: 57513 },{14 label: 'handheld',15 enter: 576,16 exit: 76717 },{18 label: 'tablet',19 enter: 768,20 exit: 99121 },{22 label: 'laptop',23 enter: 992,24 exit: 119925 },{26 label: 'desktop',27 enter: 1200,28 exit: 1000029 }30 ]);31 jRes.addFunc([32 {33 breakpoint: 'desktop',34 enter: function() { $respondEl.addClass('device-xl'); },35 exit: function() { $respondEl.removeClass('device-xl'); }36 },{37 breakpoint: 'laptop',38 enter: function() { $respondEl.addClass('device-lg'); },39 exit: function() { $respondEl.removeClass('device-lg'); }40 },{41 breakpoint: 'tablet',42 enter: function() { $respondEl.addClass('device-md'); },43 exit: function() { $respondEl.removeClass('device-md'); }44 },{45 breakpoint: 'handheld',46 enter: function() { $respondEl.addClass('device-sm'); },47 exit: function() { $respondEl.removeClass('device-sm'); }48 },{49 breakpoint: 'smallest',50 enter: function() { $respondEl.addClass('device-xs'); },51 exit: function() { $respondEl.removeClass('device-xs'); }52 }53 ]);...

Full Screen

Full Screen

comment-reply.js

Source:comment-reply.js Github

copy

Full Screen

1var addComment = {2 moveForm : function(commId, parentId, respondId, postId) {3 var t = this, div, comm = t.I(commId), respond = t.I(respondId), cancel = t.I('cancel-comment-reply-link'), parent = t.I('comment_parent'), post = t.I('comment_post_ID');4 if ( ! comm || ! respond || ! cancel || ! parent )5 return;6 t.respondId = respondId;7 postId = postId || false;8 if ( ! t.I('wp-temp-form-div') ) {9 div = document.createElement('div');10 div.id = 'wp-temp-form-div';11 div.style.display = 'none';12 respond.parentNode.insertBefore(div, respond);13 }14 comm.parentNode.insertBefore(respond, comm.nextSibling);15 if ( post && postId )16 post.value = postId;17 parent.value = parentId;18 cancel.style.display = '';19 cancel.onclick = function() {20 var t = addComment, temp = t.I('wp-temp-form-div'), respond = t.I(t.respondId);21 if ( ! temp || ! respond )22 return;23 t.I('comment_parent').value = '0';24 temp.parentNode.insertBefore(respond, temp);25 temp.parentNode.removeChild(temp);26 this.style.display = 'none';27 this.onclick = null;28 return false;29 };30 try { t.I('comment').focus(); }31 catch(e) {}32 return false;33 },34 I : function(e) {35 return document.getElementById(e);36 }...

Full Screen

Full Screen

comment-reply.dev.js

Source:comment-reply.dev.js Github

copy

Full Screen

1addComment = {2 moveForm : function(commId, parentId, respondId, postId) {3 var t = this, div, comm = t.I(commId), respond = t.I(respondId), cancel = t.I('cancel-comment-reply-link'), parent = t.I('comment_parent'), post = t.I('comment_post_ID');4 if ( ! comm || ! respond || ! cancel || ! parent )5 return;6 t.respondId = respondId;7 postId = postId || false;8 if ( ! t.I('wp-temp-form-div') ) {9 div = document.createElement('div');10 div.id = 'wp-temp-form-div';11 div.style.display = 'none';12 respond.parentNode.insertBefore(div, respond);13 }14 comm.parentNode.insertBefore(respond, comm.nextSibling);15 if ( post && postId )16 post.value = postId;17 parent.value = parentId;18 cancel.style.display = '';19 cancel.onclick = function() {20 var t = addComment, temp = t.I('wp-temp-form-div'), respond = t.I(t.respondId);21 if ( ! temp || ! respond )22 return;23 t.I('comment_parent').value = '0';24 temp.parentNode.insertBefore(respond, temp);25 temp.parentNode.removeChild(temp);26 this.style.display = 'none';27 this.onclick = null;28 return false;29 }30 try { t.I('comment').focus(); }31 catch(e) {}32 return false;33 },34 I : function(e) {35 return document.getElementById(e);36 }...

Full Screen

Full Screen

reply.js

Source:reply.js Github

copy

Full Screen

1addReply = {2 moveForm : function(replyId, parentId, respondId, postId) {3 var t = this, div, reply = t.I(replyId), respond = t.I(respondId), cancel = t.I('bbp-cancel-reply-to-link'), parent = t.I('bbp_reply_to'), post = t.I('bbp_topic_id');4 if ( ! reply || ! respond || ! cancel || ! parent )5 return;6 t.respondId = respondId;7 postId = postId || false;8 if ( ! t.I('bbp-temp-form-div') ) {9 div = document.createElement('div');10 div.id = 'bbp-temp-form-div';11 div.style.display = 'none';12 respond.parentNode.insertBefore(div, respond);13 }14 reply.parentNode.insertBefore(respond);15 if ( post && postId )16 post.value = postId;17 parent.value = parentId;18 cancel.style.display = '';19 cancel.onclick = function() {20 var t = addReply, temp = t.I('bbp-temp-form-div'), respond = t.I(t.respondId);21 if ( ! temp || ! respond )22 return;23 t.I('bbp_reply_to').value = '0';24 temp.parentNode.insertBefore(respond, temp);25 temp.parentNode.removeChild(temp);26 this.style.display = 'none';27 this.onclick = null;28 return false;29 }30 try { t.I('bbp_reply_content').focus(); }31 catch(e) {}32 return false;33 },34 I : function(e) {35 return document.getElementById(e);36 }...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1const puppeteer = require('puppeteer');2const devices = require('puppeteer/DeviceDescriptors');3(async () => {4 const browser = await puppeteer.launch();5 const page = await browser.newPage();6 await page.emulate(devices['iPhone 6']);7 await page.screenshot({path: 'example.png'});8 await browser.close();9})();10const puppeteer = require('puppeteer');11const devices = require('puppeteer/DeviceDescriptors');12(async () => {13 const browser = await puppeteer.launch();14 const page = await browser.newPage();15 await page.emulate(devices['iPhone 6']);16 await page.screenshot({path: 'example.png'});17 await browser.close();18})();19const puppeteer = require('puppeteer');20const devices = require('puppeteer/DeviceDescriptors');21(async () => {22 const browser = await puppeteer.launch();23 const page = await browser.newPage();24 await page.emulate(devices['iPhone 6']);25 await page.screenshot({path: 'example.png'});26 await browser.close();27})();28const puppeteer = require('puppeteer');29const devices = require('puppeteer/DeviceDescriptors');30(async () => {31 const browser = await puppeteer.launch();32 const page = await browser.newPage();33 await page.emulate(devices['iPhone 6']);34 await page.screenshot({path: 'example.png'});35 await browser.close();36})();37const puppeteer = require('puppeteer');38const devices = require('puppeteer/DeviceDescriptors');39(async () => {40 const browser = await puppeteer.launch();41 const page = await browser.newPage();42 await page.emulate(devices['iPhone 6']);43 await page.screenshot({path: 'example.png'});44 await browser.close();45})();

Full Screen

Using AI Code Generation

copy

Full Screen

1const puppeteer = require('puppeteer');2(async () => {3 const browser = await puppeteer.launch();4 const page = await browser.newPage();5 await page.pdf({path: 'google.pdf', format: 'A4'});6 await browser.close();7})();8const puppeteer = require('puppeteer');9(async () => {10 const browser = await puppeteer.launch();11 const page = await browser.newPage();12 await page.pdf({path: 'google.pdf', format: 'A4'});13 await browser.close();14})();15const puppeteer = require('puppeteer');16(async () => {17 const browser = await puppeteer.launch();18 const page = await browser.newPage();19 await page.pdf({path: 'google.pdf', format: 'A4'});20 await browser.close();21})();22const puppeteer = require('puppeteer');23(async () => {24 const browser = await puppeteer.launch();25 const page = await browser.newPage();26 await page.pdf({path: 'google.pdf', format: 'A4'});27 await browser.close();28})();29const puppeteer = require('puppeteer');30(async () => {31 const browser = await puppeteer.launch();32 const page = await browser.newPage();33 await page.pdf({path: 'google.pdf', format: 'A4'});34 await browser.close();35})();36const puppeteer = require('puppeteer');37(async () => {38 const browser = await puppeteer.launch();39 const page = await browser.newPage();40 await page.pdf({path: 'google.pdf', format: 'A4'});41 await browser.close();42})();

Full Screen

Using AI Code Generation

copy

Full Screen

1(async () => {2 const browser = await puppeteer.launch({ headless: false });3 const page = await browser.newPage();4 await page.type('input[title="Search"]', 'Puppeteer');5 await page.keyboard.press('Enter');6 await page.waitForNavigation();7 await page.screenshot({ path: 'example.png' });8 await browser.close();9})();10(async () => {11 const browser = await puppeteer.launch({ headless: false });12 const page = await browser.newPage();13 await page.setRequestInterception(true);14 page.on('request', (req) => {15 if (req.resourceType() === 'image')16 req.abort();17 req.continue();18 });19 await page.type('input[title="Search"]', 'Puppeteer');20 await page.keyboard.press('Enter');21 await page.waitForNavigation();22 await page.screenshot({ path: 'example.png' });23 await browser.close();24})();

Full Screen

Using AI Code Generation

copy

Full Screen

1const puppeteer = require('puppeteer');2const fs = require('fs');3const path = require('path');4(async () => {5 const browser = await puppeteer.launch();6 const page = await browser.newPage();7 await page.goto('

Full Screen

Using AI Code Generation

copy

Full Screen

1const puppeteer = require('puppeteer');2const fs = require('fs');3const path = require('path');4(async () => {5 const browser = await puppeteer.launch();6 const page = await browser.newPage();7 await page.goto(url);8 const html = await page.content();9 fs.writeFileSync(path.join(__dirname, 'google.html'), html);10 await browser.close();11})();

Full Screen

Using AI Code Generation

copy

Full Screen

1const puppeteer = require('puppeteer');2const fs = require('fs');3const path = require('path');4const { promisify } = require('util');5const writeFile = promisify(fs.writeFile);6async function run() {7 const browser = await puppeteer.launch({8 });9 const page = await browser.newPage();10 await page.type('input[title="Search"]', 'puppeteer');11 await page.keyboard.press('Enter');12 await page.waitForNavigation();13 await page.waitForSelector('h3');14 const links = await page.evaluate(() => {15 const anchors = Array.from(document.querySelectorAll('h3'));16 return anchors.map((anchor) => anchor.textContent);17 });18 await writeFile(19 path.join(__dirname, 'output', 'google.json'),20 JSON.stringify(links, null, 2)21 );22 await browser.close();23}24run();25{26 "scripts": {27 },28 "dependencies": {29 }30}

Full Screen

Using AI Code Generation

copy

Full Screen

1const puppeteer = require("puppeteer");2const fs = require("fs");3const path = require("path");4const createPDF = async (url, output, options) => {5 const browser = await puppeteer.launch({6 });7 const page = await browser.newPage();8 await page.goto(url, { waitUntil: "networkidle0" });9 const pdf = await page.pdf(options);10 await browser.close();11 fs.writeFile(output, pdf, (err) => {12 if (err) throw err;13 console.log("The file has been saved!");14 });15};16const output = path.join(__dirname, "test.pdf");17const options = {18};19createPDF(url, output, options);

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 Puppeteer 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