Best JavaScript code snippet using playwright-internal
vehicular.js
Source:vehicular.js
...31 if(tipoMoneda==SOLES){32 //Soles33 switch (tipoProducto) {34 case 46://Tradicional35 setSelector($("plazoCreditoVehicular"), RANGO_PLAZO_CREDITO_SIM_VEH_TRA_SOLES,'Plazo de Cr\u00e9dito');36 setSelector($("valorInicial"), RANGO_CUOTA_INICIAL_SIM_VEH_TRA_SOLES,"%");37 setSelector($("valorAuto"), RANGO_VALOR_VEHICULO_SIM_VEH_TRA_SOLES,"S/.");38 break;39 case 51://Casi nuevo40 setSelector($("plazoCreditoVehicular"), RANGO_PLAZO_CREDITO_SIM_VEH_CNU_SOLES,'Plazo de Cr\u00e9dito');41 setSelector($("valorInicial"), RANGO_CUOTA_INICIAL_SIM_VEH_CNU_SOLES,"%");42 setSelector($("valorAuto"), RANGO_VALOR_VEHICULO_SIM_VEH_CNU_SOLES,"S/.");43 break;44 case 52://Especial 45 setSelector($("plazoCreditoVehicular"), RANGO_PLAZO_CREDITO_SIM_VEH_ESP_SOLES,'Plazo de Cr\u00e9dito');46 setSelector($("valorInicial"), RANGO_CUOTA_INICIAL_SIM_VEH_ESP_SOLES,"%");47 setSelector($("valorAuto"), RANGO_VALOR_VEHICULO_SIM_VEH_ESP_SOLES,"S/.");48 break;49 case 53://Compra inteligente50 setSelector($("plazoCreditoVehicular"), RANGO_PLAZO_CREDITO_SIM_VEH_CIN_SOLES,'Plazo de Cr\u00e9dito');51 setSelector($("valorInicial"), RANGO_CUOTA_INICIAL_SIM_VEH_CIN_SOLES,"%");52 setSelector($("valorAuto"), RANGO_VALOR_VEHICULO_SIM_VEH_CIN_SOLES,"S/.");53 break;54 }55 }else if(tipoMoneda==DOLARES){56 //Dolares57 switch (tipoProducto) {58 case 46://Tradicional59 setSelector($("plazoCreditoVehicular"), RANGO_PLAZO_CREDITO_SIM_VEH_TRA_DOLARES,'meses');60 setSelector($("valorInicial"), RANGO_CUOTA_INICIAL_SIM_VEH_TRA_DOLARES,"%");61 setSelector($("valorAuto"), RANGO_VALOR_VEHICULO_SIM_VEH_TRA_DOLARES,"$");62 break;63 case 51://Casi nuevo64 setSelector($("plazoCreditoVehicular"), RANGO_PLAZO_CREDITO_SIM_VEH_CNU_DOLARES,'meses');65 setSelector($("valorInicial"), RANGO_CUOTA_INICIAL_SIM_VEH_CNU_DOLARES,"%");66 setSelector($("valorAuto"), RANGO_VALOR_VEHICULO_SIM_VEH_CNU_DOLARES,"$");67 break;68 case 52://Especial69 setSelector($("plazoCreditoVehicular"), RANGO_PLAZO_CREDITO_SIM_VEH_ESP_DOLARES,'meses');70 setSelector($("valorInicial"), RANGO_CUOTA_INICIAL_SIM_VEH_ESP_DOLARES,"%");71 setSelector($("valorAuto"), RANGO_VALOR_VEHICULO_SIM_VEH_ESP_DOLARES,"$");72 break;73 case 53://Compra inteligente74 setSelector($("plazoCreditoVehicular"), RANGO_PLAZO_CREDITO_SIM_VEH_CIN_DOLARES,'meses');75 setSelector($("valorInicial"), RANGO_CUOTA_INICIAL_SIM_VEH_CIN_DOLARES,"%");76 setSelector($("valorAuto"), RANGO_VALOR_VEHICULO_SIM_VEH_CIN_DOLARES,"$");77 break;78 }79 }80};81var loadRangosSessionVehicular = function(tipoMoneda,tipoProducto,step){82 83 if(tipoMoneda==SOLES){84 //Soles85 switch (tipoProducto) {86 case 46://Tradicional87 setSelector($("plazoCreditoVehicular"), RANGO_PLAZO_CREDITO_SIM_VEH_TRA_SOLES,'Plazo de Cr\u00e9dito', null,step.plazoCredito );88 setSelector($("valorInicial"), RANGO_CUOTA_INICIAL_SIM_VEH_TRA_SOLES,"%",null,step.cuotaInicial );89 setSelector($("valorAuto"), RANGO_VALOR_VEHICULO_SIM_VEH_TRA_SOLES,"S/.",null,step.valorVehiculo );90 break;91 case 51://Casi nuevo92 setSelector($("plazoCreditoVehicular"), RANGO_PLAZO_CREDITO_SIM_VEH_CNU_SOLES,'Plazo de Cr\u00e9dito',null,step.plazoCredito);93 setSelector($("valorInicial"), RANGO_CUOTA_INICIAL_SIM_VEH_CNU_SOLES,"%",null,step.cuotaInicial );94 setSelector($("valorAuto"), RANGO_VALOR_VEHICULO_SIM_VEH_CNU_SOLES,"S/.",null,step.valorVehiculo);95 break;96 case 52://Especial 97 setSelector($("plazoCreditoVehicular"), RANGO_PLAZO_CREDITO_SIM_VEH_ESP_SOLES,'Plazo de Cr\u00e9dito',null,step.plazoCredito);98 setSelector($("valorInicial"), RANGO_CUOTA_INICIAL_SIM_VEH_ESP_SOLES,"%",null,step.cuotaInicial );99 setSelector($("valorAuto"), RANGO_VALOR_VEHICULO_SIM_VEH_ESP_SOLES,"S/.",null,step.valorVehiculo);100 break;101 case 53://Compra inteligente102 setSelector($("plazoCreditoVehicular"), RANGO_PLAZO_CREDITO_SIM_VEH_CIN_SOLES,'Plazo de Cr\u00e9dito',null,step.plazoCredito);103 setSelector($("valorInicial"), RANGO_CUOTA_INICIAL_SIM_VEH_CIN_SOLES,"%",null,step.cuotaInicial );104 setSelector($("valorAuto"), RANGO_VALOR_VEHICULO_SIM_VEH_CIN_SOLES,"S/.",null,step.valorVehiculo);105 break;106 }107 }else if(tipoMoneda==DOLARES){108 //Dolares109 switch (tipoProducto) {110 case 46://Tradicional111 setSelector($("plazoCreditoVehicular"), RANGO_PLAZO_CREDITO_SIM_VEH_TRA_DOLARES,'Plazo de Cr\u00e9dito',null,step.plazoCredito);112 setSelector($("valorInicial"), RANGO_CUOTA_INICIAL_SIM_VEH_TRA_DOLARES,"%",null,step.cuotaInicial );113 setSelector($("valorAuto"), RANGO_VALOR_VEHICULO_SIM_VEH_TRA_DOLARES,"$",null,step.valorVehiculo);114 break;115 case 51://Casi nuevo116 setSelector($("plazoCreditoVehicular"), RANGO_PLAZO_CREDITO_SIM_VEH_CNU_DOLARES,'Plazo de Cr\u00e9dito',null,step.plazoCredito);117 setSelector($("valorInicial"), RANGO_CUOTA_INICIAL_SIM_VEH_CNU_DOLARES,"%",null,step.cuotaInicial );118 setSelector($("valorAuto"), RANGO_VALOR_VEHICULO_SIM_VEH_CNU_DOLARES,"$",null,step.valorVehiculo);119 break;120 case 52://Especial121 setSelector($("plazoCreditoVehicular"), RANGO_PLAZO_CREDITO_SIM_VEH_ESP_DOLARES,'Plazo de Cr\u00e9dito',null,step.plazoCredito);122 setSelector($("valorInicial"), RANGO_CUOTA_INICIAL_SIM_VEH_ESP_DOLARES,"%",null,step.cuotaInicial );123 setSelector($("valorAuto"), RANGO_VALOR_VEHICULO_SIM_VEH_ESP_DOLARES,"$",null,step.valorVehiculo);124 break;125 case 53://Compra inteligente126 setSelector($("plazoCreditoVehicular"), RANGO_PLAZO_CREDITO_SIM_VEH_CIN_DOLARES,'Plazo de Cr\u00e9dito',null,step.plazoCredito);127 setSelector($("valorInicial"), RANGO_CUOTA_INICIAL_SIM_VEH_CIN_DOLARES,"%",null,step.cuotaInicial );128 setSelector($("valorAuto"), RANGO_VALOR_VEHICULO_SIM_VEH_CIN_DOLARES,"$",null,step.valorVehiculo);129 break;130 }131 }132};133var setOptionVehicular = function(e){134 var tipoMonedaActual=$('hoptTipMonedaVehicular').value.toInt();135 var tipoCreditoActual=$('hoptTipCreditoVehicular').value.toInt();136 loadRangoVehicular(tipoMonedaActual,tipoCreditoActual);137};138var ValidkeyVehicular = function(e){139 var tipoDocSel=$('hcmbTipDocVehicular').value;140 if(tipoDocSel==0){141 /*$('errorVehicularPaso1').set('html','*Seleccione un tipo de documento.');*/142 return false;...
ProfileImagesCrop.js
Source:ProfileImagesCrop.js
12$(document).ready(function () {3 var jcrop_api;4 5 function showCoordsBanner(c) {6 $('#ProfileBanner_ImageCrop_XCoord').val(c.x);7 $('#ProfileBanner_ImageCrop_YCoord').val(c.y);8 $('#ProfileBanner_ImageCrop_Width').val(c.w);9 $('#ProfileBanner_ImageCrop_Height').val(c.h);10 };11 function showCoordsProfile(c) {12 $('#Image_ImageCrop_XCoord').val(c.x);13 $('#Image_ImageCrop_YCoord').val(c.y);14 $('#Image_ImageCrop_Width').val(c.w);15 $('#Image_ImageCrop_Height').val(c.h);16 };17 function showCoordsConditionBanner(c) {18 $('#ConditionBanner_ImageCrop_XCoord').val(c.x);19 $('#ConditionBanner_ImageCrop_YCoord').val(c.y);20 $('#ConditionBanner_ImageCrop_Width').val(c.w);21 $('#ConditionBanner_ImageCrop_Height').val(c.h);22 };23 function showCoordsConditionDirectoryImage(c) {24 $('#ConditionDirectoryImage_ImageCrop_XCoord').val(c.x);25 $('#ConditionDirectoryImage_ImageCrop_YCoord').val(c.y);26 $('#ConditionDirectoryImage_ImageCrop_Width').val(c.w);27 $('#ConditionDirectoryImage_ImageCrop_Height').val(c.h);28 };29 function showCoordsUpdateUserPoseImages(c) {30 $('#UpdateUserPoseImages_ImageCrop_XCoord').val(c.x);31 $('#UpdateUserPoseImages_ImageCrop_YCoord').val(c.y);32 $('#UpdateUserPoseImages_ImageCrop_Width').val(c.w);33 $('#UpdateUserPoseImages_ImageCrop_Height').val(c.h);34 };35 36 function drawCroppedImage(prefix) {37 var widthCrop = $("#" + prefix + "ImageCrop_Width").val();38 var heightcrop = $("#" + prefix + "ImageCrop_Height").val();39 var xcrop = $("#" + prefix + "ImageCrop_XCoord").val();40 var ycrop = $("#" + prefix + "ImageCrop_YCoord").val();41 var canvas = document.getElementById(prefix + "signupcanvascanvas");42 var context = canvas.getContext('2d');43 canvas.width = widthCrop;44 canvas.height = heightcrop;45 // Get the src of the image from the div46 var newimage = $('.jcrop-holder div div img').attr("src");47 var imageObj = new Image();48 imageObj.src = newimage;49 // draw the image with offset50 context.drawImage(imageObj, xcrop, ycrop, widthCrop, heightcrop, 0, 0, widthCrop, heightcrop);51 };52 function swapToInPageImage(prefix) {53 $("#" + prefix + "signupcontainer").parent().children("div").hide();54 $("#" + prefix + "signupcanvas").show();55 };56 function bindPreviewSignup(e, coordFunction, aspectRatio, setSelector, prefix) {57 var screenWidth = $("body").width();58 59 //Extends the pre filled box if its a ipad or smaller device.60 if (screenWidth < 1100) {61 var tempimgUploaded = new Image();62 tempimgUploaded.src = e.srcElement.result;63 if (setSelector[2] == setSelector[3]) {64 if (tempimgUploaded.width > 1000) {65 setSelector[2] = setSelector[2] * 2;66 setSelector[3] = setSelector[3] * 2;67 }68 if (tempimgUploaded.width > 2000) {69 setSelector[2] = setSelector[2] * 1.5;70 setSelector[3] = setSelector[3] * 1.5;71 }72 if (tempimgUploaded.width > 3000) {73 setSelector[2] = setSelector[2] * 1.5;74 setSelector[3] = setSelector[3] * 1.5;75 }76 } else {77 if (tempimgUploaded.width > 2000) {78 setSelector[2] = setSelector[2] * 2;79 setSelector[3] = setSelector[3] * 2;80 }81 if (tempimgUploaded.width > 3000) {82 setSelector[2] = setSelector[2] * 1.5;83 setSelector[3] = setSelector[3] * 1.5;84 }85 if (tempimgUploaded.width > 4000) {86 setSelector[2] = setSelector[2] * 1.5;87 setSelector[3] = setSelector[3] * 1.5;88 }89 }90 }91 $('#preview').Jcrop({92 onChange: coordFunction,93 onSelect: coordFunction,94 boxWidth: screenWidth,95 aspectRatio: aspectRatio96 }, function () {97 jcrop_api = this;98 });99 100 jcrop_api.setImage(e.target.result);101 $.fancybox(102 {103 href: "#cropfancybox",104 scrolling: 'none',105 autoSize: false, //Fix for FireFox Load106 autoDimensions: false,107 height: 'auto',108 width: 'auto',109 afterShow: function () {110 $('.fancybox-outer').append(111 $('<div>Drag the corners of the above box to crop your photo</div>', { 'style': 'display:inline-block; width:100%; padding:10px 0 0 0; margin-top: 5px' }).append(112 $('<input/>', { 'class': 'button', 'type': 'button', 'value': 'Finished Cropping', 'onClick': '$.fancybox.close(); $(\'#PleaseWait\').hide();', 'style': 'float:right;' }))113 );114 jcrop_api.setSelect(setSelector);115 },116 afterClose: function () {117 drawCroppedImage(prefix);118 swapToInPageImage(prefix);119 }120 });121 };122 function bindPreview(e, coordFunction, aspectRatio, setSelector, saveMessage, formId) {123 var screenWidth = $("body").width();124 $('#preview').Jcrop({125 onChange: coordFunction,126 onSelect: coordFunction,127 boxWidth: screenWidth,128 aspectRatio: aspectRatio129 }, function () {130 jcrop_api = this;131 });132 jcrop_api.setImage(e.target.result);133 $.fancybox(134 {135 href: "#cropfancybox",136 scrolling: 'none',137 autoSize: false, //Fix for FireFox Load138 autoDimensions: false,139 height: 'auto',140 width: 'auto',141 afterShow: function () {142 $('.fancybox-outer').append(143 $('<div>Drag the corners of the above box to crop your photo</div>', { 'style': 'display:inline-block; width:100%; padding:10px 0 0 0; margin-top: 5px' }).append(144 $('<input/>', { 'class': 'button', 'type': 'button', 'value': 'Finished Cropping', 'onClick': '$.fancybox.close(); $(\'' + formId + '\').submit(); $(\'#PleaseWait\').show();', 'style': 'float:right;' }))145 );146 jcrop_api.setSelect(setSelector);147 }148 });149 };150 $('#File').change(function (evt) {151 if (window.FileReader) {152 var f = evt.target.files[0];153 var reader = new FileReader();154 reader.onload = function (e) {155 bindPreview(e, showCoordsBanner, 3 / 1, [0, 0, 200, 200], 'profilebannerSave', '#update-banner-form');156 }157 reader.readAsDataURL(f);158 }159 });160 $("#ProfileBanner_signupcontainer").change(function (evt) {161 if (window.FileReader) {162 if (evt.target.files[0].name.match(/\.(jpg|jpeg|png|gif)$/i)) {163 var f = evt.target.files[0];164 var reader = new FileReader();165 reader.onload = function (e) {166 bindPreviewSignup(e, showCoordsBanner, 3 / 1, [0, 0, 710, 240], "ProfileBanner_");167 }168 reader.readAsDataURL(f);169 } else {170 //can place alerts here171 }172 }173 });174 //Click event for the editing of a image175 $(".signupbannerimagechange").click(function () {176 $("#ProfileBanner_NewImage_PostedFile").click();177 });178 $("#Image_signupcontainer").change(function (evt) {179 if (window.FileReader) {180 if (evt.target.files[0].name.match(/\.(jpg|jpeg|png|gif)$/i)) {181 182 var f = evt.target.files[0];183 var reader = new FileReader();184 reader.onload = function (e) {185 bindPreviewSignup(e, showCoordsProfile, 1 / 1, [0, 0, 240, 240], "Image_");186 }187 reader.readAsDataURL(f);188 } else {189 //can place alerts here190 }191 }192 });193 //Click event for the editing of a image194 $(".signupprofileimagechange").click(function () {195 $("#Image_NewImage_PostedFile").click();196 });197 $('#ConditionBanner').change(function (evt) {198 if (window.FileReader) {199 var f = evt.target.files[0];200 var reader = new FileReader();201 reader.onload = function (e) {202 bindPreview(e, showCoordsConditionBanner, 179 / 94, [0, 0, 716, 376], 'conditionbannerSave', '#update-condition-banner-form');203 }204 reader.readAsDataURL(f);205 }206 });207 $('#ConditionDirectoryImage').change(function (evt) {208 if (window.FileReader) {209 var f = evt.target.files[0];210 var reader = new FileReader();211 reader.onload = function (e) {212 bindPreview(e, showCoordsConditionDirectoryImage, 133 / 59, [0, 0, 266, 118], 'conditiondirectoryimageSave', '#update-condition-directory-image-form');213 }214 reader.readAsDataURL(f);215 }216 });217 $('#UserPoseImages').change(function (evt) {218 if (window.FileReader) {219 if (evt.target.files[0].name.match(/\.(jpg|jpeg|png|gif)$/i)) {220 var f = evt.target.files[0];221 var reader = new FileReader();222 reader.onload = function (e) {223 bindPreview(e, showCoordsUpdateUserPoseImages, 1 / 1, [0, 0, 600, 600], 'conditiondirectoryimageSave', '#update-condition-directory-image-form');224 }225 reader.readAsDataURL(f);226 } else {227 //Error file type228 }229 }230 });231 232 $('#profileImage').change(function (evt) {233 if (window.FileReader) {234 var f = evt.target.files[0];235 var reader = new FileReader();236 reader.onload = function (e) {237 bindPreview(e, showCoordsProfile, 1 / 1, [0, 0, 200, 200], 'profileImageSave', '#update-profile-image-form');238 }239 reader.readAsDataURL(f);240 }241 });...
integration.test.js
Source:integration.test.js
1const assert = require('assert');2const mockServer = require('../mock/server');3const Consumer = require('../../lib/consumer');4const Producer = require('../../lib/producer');5const Task = require('../../lib/task');6const REDIS_CONF = {7 host: 'redis-12419.c44.us-east-1-2.ec2.cloud.redislabs.com',8 port: 12419,9 password: 'X2AcjziaOOYPppWFOPiP4rmzZ9RFLViv'10};11const MOCK_SERVER_PORT = 8181;12const TEST_CHANNEL_1 = '_tc1_' + (Math.random() * 1000000).toFixed();13const TEST_CHANNEL_2 = '_tc2_' + (Math.random() * 1000000).toFixed();14const TEST_CHANNEL_3 = '_tc3_' + (Math.random() * 1000000).toFixed();15describe('integration test', function() {16 before(function () {17 mockServer.listen(MOCK_SERVER_PORT);18 });19 after(function () {20 mockServer.close(MOCK_SERVER_PORT);21 });22 describe('consumer & producer module test in plain mode', function() {23 this.timeout(20000);24 const setSelector = '.container ul li';25 it('test plain mode producer', function (done) {26 console.info(`test channel: ${TEST_CHANNEL_1}`);27 let myProducer = new Producer({28 channel: TEST_CHANNEL_1,29 dbConf: {30 redis: REDIS_CONF31 }32 });33 let task = new Task({34 spiderType: 'plain',35 url: `http://127.0.0.1:${MOCK_SERVER_PORT}/?num=1`,36 targets: [37 {38 selector: setSelector,39 type: 'text',40 field: 'name'41 }42 ]43 })44 myProducer.generateTask(task).then(() => {45 done();46 });47 });48 it('test consumer for plain crawling', function (done) {49 class TestConsumer2 extends Consumer {50 constructor(option) {51 super(option);52 }53 afterCrawlRequest(result) {54 done();55 }56 }57 let myConsumer = new TestConsumer2({58 channel: TEST_CHANNEL_1,59 sleepTime: 5000,60 deviceType: 'pc',61 userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36',62 customHeaders: {63 'Referer': 'https://www.zhuyingda.com/'64 },65 dbConf: {66 redis: REDIS_CONF67 }68 });69 try {70 myConsumer.startConsume();71 }72 catch (err) {73 console.log('plain mode consumer executing got error');74 done();75 }76 });77 });78 describe('consumer & producer module test in browser(puppeteer) mode', function() {79 this.timeout(60000);80 const setSelector = '.container ul li';81 it('test browser(puppeteer) mode producer', function (done) {82 console.info(`test channel: ${TEST_CHANNEL_2}`);83 let myProducer = new Producer({84 channel: TEST_CHANNEL_2,85 dbConf: {86 redis: REDIS_CONF87 }88 });89 let task = new Task({90 spiderType: 'browser',91 engineType: 'puppeteer',92 url: `http://127.0.0.1:${MOCK_SERVER_PORT}/?num=1`,93 targets: [94 {95 selector: setSelector,96 type: 'text',97 field: 'name'98 }99 ],100 actions: [101 {102 type: "waitAfterPageLoading",103 value: 500104 }105 ]106 })107 myProducer.generateTask(task).then(() => {108 done();109 });110 });111 it('test consumer for browser(puppeteer) crawling', function (done) {112 class TestConsumer extends Consumer {113 constructor(option) {114 super(option);115 }116 afterCrawlRequest(result) {117 if (result && result.name) {118 assert.strictEqual(17, result.name.length);119 assert.strictEqual(setSelector, result.name[0].selector);120 assert.strictEqual('Kodiak', result.name[0].text);121 assert.strictEqual(0, result.name[0].index);122 assert.strictEqual(setSelector, result.name[1].selector);123 assert.strictEqual('Cheetah', result.name[1].text);124 assert.strictEqual(1, result.name[1].index);125 assert.strictEqual(setSelector, result.name[2].selector);126 assert.strictEqual('Puma', result.name[2].text);127 assert.strictEqual(2, result.name[2].index);128 done();129 }130 else {131 console.error('test consumer for browser crawling unit error');132 done(new Error());133 }134 }135 }136 let myConsumer = new TestConsumer({137 channel: TEST_CHANNEL_2,138 sleepTime: 5000,139 deviceType: 'pc',140 userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36',141 customHeaders: {142 'Referer': 'https://www.zhuyingda.com/'143 },144 dbConf: {145 redis: REDIS_CONF146 }147 });148 try {149 myConsumer.startConsume();150 }151 catch (err) {152 console.log('browser mode consumer executing got error');153 done();154 }155 });156 });157 describe('consumer & producer module test in browser(playwright) mode', function() {158 this.timeout(60000);159 const setSelector = '.container ul li';160 it('test browser(playwright) mode producer', function (done) {161 console.info(`test channel: ${TEST_CHANNEL_3}`);162 let myProducer = new Producer({163 channel: TEST_CHANNEL_3,164 dbConf: {165 redis: REDIS_CONF166 }167 });168 let task = new Task({169 spiderType: 'browser',170 engineType: 'playwright',171 browserType: 'chromium',172 url: `http://127.0.0.1:${MOCK_SERVER_PORT}/?num=1`,173 targets: [174 {175 selector: setSelector,176 type: 'text',177 field: 'name'178 }179 ],180 actions: [181 {182 type: "waitAfterPageLoading",183 value: 500184 }185 ]186 })187 myProducer.generateTask(task).then(() => {188 done();189 });190 });191 it('test consumer for browser(playwright) crawling', function (done) {192 class TestConsumer extends Consumer {193 constructor(option) {194 super(option);195 }196 afterCrawlRequest(result) {197 if (result && result.name) {198 assert.strictEqual(17, result.name.length);199 assert.strictEqual(setSelector, result.name[0].selector);200 assert.strictEqual('Kodiak', result.name[0].text);201 assert.strictEqual(0, result.name[0].index);202 assert.strictEqual(setSelector, result.name[1].selector);203 assert.strictEqual('Cheetah', result.name[1].text);204 assert.strictEqual(1, result.name[1].index);205 assert.strictEqual(setSelector, result.name[2].selector);206 assert.strictEqual('Puma', result.name[2].text);207 assert.strictEqual(2, result.name[2].index);208 done();209 }210 else {211 console.error('test consumer for browser crawling unit error');212 done(new Error());213 }214 }215 }216 let myConsumer = new TestConsumer({217 channel: TEST_CHANNEL_3,218 sleepTime: 5000,219 deviceType: 'pc',220 userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36',221 customHeaders: {222 'Referer': 'https://www.zhuyingda.com/'223 },224 dbConf: {225 redis: REDIS_CONF226 }227 });228 try {229 myConsumer.startConsume();230 }231 catch (err) {232 console.log('browser mode consumer executing got error');233 done();234 }235 });236 });...
checkout.js
Source:checkout.js
...33 /**34 * Remove table content35 */36 this.clearHTML = function() {37 this.setSelector('table tbody');38 this.selection.empty();39 };40 /**41 * Delete specific table row from table42 * @param {string} selector43 */44 this.deleteRow = function(selector) {45 this.setSelector(selector);46 this.selection.remove();47 };48 this.calculateTotal = function(){49 var total = 0;50 for (var i = 0; i < cart.products.length; ++i) {51 total += (cart.products[i].price * cart.products[i].quantity);52 }53 return total;54 };55 this.init = function(){56 // Clear table content57 this.clearHTML();58 this.setSelector('table');59 // Show table in-case if it was hidden60 this.selection.show();61 this.setSelector('.emptyCart');62 // Remove div empty cart if exist63 this.selection.remove();64 var htemp = this.generateHTML(cart.products);65 if(htemp.length > 0){66 this.append('table tbody', this.generateHTML(cart.products));67 this.setSelector('.check_total');68 this.selection.show();69 this.setSelector('.total .value');70 this.selection.text(this.calculateTotal());71 }else{72 this.setSelector('table');73 this.selection.hide();74 this.append('', '<div class="emptyCart">Cart is empty</div>');75 this.setSelector('.check_total');76 this.selection.hide();77 }78 };79 this.init();80 /**81 * Click event for plus button, using delegate event handler from jquery82 * to apply it for future created elements83 * What I'm doing here is :84 * 1- Get row id form html85 * 2- Get object matching that id form cart.products86 * 3- Get current quantity value then increase it87 * 4- Update html with new value88 * 5- Update object in cart.products89 * Updating cart.products is very important, to save values when switching to 90 * another page 91 */92 $('#' + this.id).delegate('.plus', 'click', function(e) {93 e.stopImmediatePropagation();94 //console.log('clicked');95 // Get element id96 var id = $(this).parent().parent().attr('id');97 // Get equivalent cart object98 var cart_object = cart.getObject(id);99 // Get html element100 var quantity_element = $(this).parent().find('span');101 if (cart_object.stock > cart_object.quantity) {102 quantity_element.text(++cart_object.quantity);103 self.setSelector('.total .value');104 self.selection.text(self.calculateTotal());105 }106 // console.log(cart.products);107 });108 $('#' + this.id).delegate('.minus', 'click', function() {109 var id = $(this).parent().parent().attr('id');110 // Get equivalent cart object111 var cart_object = cart.getObject(id);112 // Get html element113 var quantity_element = $(this).parent().find('span');114 if (cart_object.quantity > 0) {115 quantity_element.text(--cart_object.quantity);116 self.setSelector('.total .value');117 self.selection.text(self.calculateTotal());118 }119 });120 $('#' + this.id).delegate('.delete', 'click', function(){121 var id = $(this).parent().parent().attr('id');122 self.deleteRow('#' + id);123 cart.remove(id);124 self.init();125 });126 $('#' + this.id).delegate('.checkout', 'click', function(e){127 e.stopImmediatePropagation();128 for (var i = 0; i < cart.products.length; ++i) {129 var id = cart.products[i].id;130 var product_object = database.getRow(id);131 product_object.stock -= cart.products[i].quantity;132 }133 self.clearHTML();134 self.setSelector('table');135 self.selection.hide();136 self.append('', '<div class="emptyCart">Cart is empty</div>');137 self.setSelector('.check_total');138 self.selection.hide();139 cart.clearCart();140 cart.updateCartCounter();141 var modal = new Modal(142 'Success',143 'Success',144 'Thank you for buying from our store, ',145 'Ok',146 function(){147 modal.hide();148 caller.switchTo('website');149 }150 );151 });...
case1.test.js
Source:case1.test.js
1const assert = require('assert');2const mockServer = require('../mock/server');3const playwright = require('../../lib/browser/playwright');4const MOCK_SERVER_PORT = 8181;5describe('playwright usage', function () {6 this.timeout(60000);7 before(function () {8 mockServer.listen(MOCK_SERVER_PORT);9 });10 after(function () {11 mockServer.close(MOCK_SERVER_PORT);12 });13 it('playwright normal usage [chromium]', function (done) {14 const setSelector = '.container ul li';15 playwright.request({16 type: 'chromium',17 url: `http://127.0.0.1:${MOCK_SERVER_PORT}/?num=1`,18 headers: {19 'User-Agent': 'test case webster'20 },21 viewPort: {22 width: 1440,23 height: 96024 },25 actions: [26 {27 type: "waitAfterPageLoading",28 value: 10029 }30 ],31 targets: [32 {33 selector: setSelector,34 type: 'text',35 field: 'name'36 }37 ]38 }).then(output => {39 const result = output.result;40 assert.strictEqual(17, result.name.length);41 assert.strictEqual(setSelector, result.name[0].selector);42 assert.strictEqual('Kodiak', result.name[0].text);43 assert.strictEqual(0, result.name[0].index);44 assert.strictEqual(setSelector, result.name[1].selector);45 assert.strictEqual('Cheetah', result.name[1].text);46 assert.strictEqual(1, result.name[1].index);47 assert.strictEqual(setSelector, result.name[2].selector);48 assert.strictEqual('Puma', result.name[2].text);49 assert.strictEqual(2, result.name[2].index);50 done();51 });52 });53 it('playwright normal usage [firefox]', function (done) {54 const setSelector = '.container ul li';55 playwright.request({56 type: 'firefox',57 url: `http://127.0.0.1:${MOCK_SERVER_PORT}/?num=1`,58 headers: {59 'User-Agent': 'test case webster'60 },61 viewPort: {62 width: 1440,63 height: 96064 },65 actions: [66 {67 type: "waitAfterPageLoading",68 value: 10069 }70 ],71 targets: [72 {73 selector: setSelector,74 type: 'text',75 field: 'name'76 }77 ]78 }).then(output => {79 const result = output.result;80 assert.strictEqual(17, result.name.length);81 assert.strictEqual(setSelector, result.name[0].selector);82 assert.strictEqual('Kodiak', result.name[0].text);83 assert.strictEqual(0, result.name[0].index);84 assert.strictEqual(setSelector, result.name[1].selector);85 assert.strictEqual('Cheetah', result.name[1].text);86 assert.strictEqual(1, result.name[1].index);87 assert.strictEqual(setSelector, result.name[2].selector);88 assert.strictEqual('Puma', result.name[2].text);89 assert.strictEqual(2, result.name[2].index);90 done();91 });92 });93 it('playwright normal usage [webkit]', function (done) {94 const setSelector = '.container ul li';95 playwright.request({96 type: 'webkit',97 url: `http://127.0.0.1:${MOCK_SERVER_PORT}/?num=1`,98 headers: {99 'User-Agent': 'test case webster'100 },101 viewPort: {102 width: 1440,103 height: 960104 },105 actions: [106 {107 type: "waitAfterPageLoading",108 value: 100109 }110 ],111 targets: [112 {113 selector: setSelector,114 type: 'text',115 field: 'name'116 }117 ]118 }).then(output => {119 const result = output.result;120 assert.strictEqual(17, result.name.length);121 assert.strictEqual(setSelector, result.name[0].selector);122 assert.strictEqual('Kodiak', result.name[0].text);123 assert.strictEqual(0, result.name[0].index);124 assert.strictEqual(setSelector, result.name[1].selector);125 assert.strictEqual('Cheetah', result.name[1].text);126 assert.strictEqual(1, result.name[1].index);127 assert.strictEqual(setSelector, result.name[2].selector);128 assert.strictEqual('Puma', result.name[2].text);129 assert.strictEqual(2, result.name[2].index);130 done();131 });132 });...
Header.js
Source:Header.js
...3const Header = ({logOut}) => {4 const [selector, setSelector] = useState(0);5 return (6 <nav className="navbar navbar-expand-lg navbar-light bg-orange" style={{ backgroundColor: "#dfdfdf", marginBottom: "15px" }}>7 <NavLink onClick={() => setSelector(0)} className="navbar-brand" to="/">UzakDers</NavLink>8 <button className="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">9 <span className="navbar-toggler-icon"></span>10 </button>11 <div className="collapse navbar-collapse" id="navbarSupportedContent">12 <ul className="navbar-nav mr-auto ml-auto ">13 <li className="nav-item" >14 <NavLink onClick={() => setSelector(0)} className="nav-link" to="/" exact activeClassName="active">Panel</NavLink>15 </li>16 <li className={selector === 1 ? "nav-item dropdown active" : "nav-item dropdown"}>17 <Link className="nav-link dropdown-toggle" to="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">18 Ekleme/Ãıkarma Menüsü</Link>19 <div className="dropdown-menu" aria-labelledby="navbarDropdown">20 <NavLink onClick={() => setSelector(1)} className="dropdown-item" to="/edit-lessons" exact activeClassName="active" >Ders</NavLink>21 <NavLink onClick={() => setSelector(1)} className="dropdown-item" to="/edit-students" exact activeClassName="active" >ÃÄrenci</NavLink>22 <NavLink onClick={() => setSelector(1)} className="dropdown-item" to="/edit-teachers" exact activeClassName="active" >ÃÄretmen</NavLink>23 <NavLink onClick={() => setSelector(1)} className="dropdown-item" to="/edit-etudes" exact activeClassName="active" >Birebir</NavLink>24 <NavLink onClick={() => setSelector(1)} className="dropdown-item" to="/edit-homeworks" exact activeClassName="active" >Ãdev</NavLink>25 <NavLink onClick={() => setSelector(1)} className="dropdown-item" to="/edit-classes" exact activeClassName="active" >Sınıf</NavLink>26 </div>27 </li>28 <li className={selector === 2 ? "nav-item dropdown active" : "nav-item dropdown"}>29 <Link className="nav-link dropdown-toggle" to="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">30 Rapor Menüsü</Link>31 <div className="dropdown-menu" aria-labelledby="navbarDropdown">32 <NavLink onClick={() => setSelector(2)} className="dropdown-item" exact activeClassName="active" to="/report-students" >ÃÄrenci</NavLink>33 <NavLink onClick={() => setSelector(2)} className="dropdown-item" exact activeClassName="active" to="/report-teachers">ÃÄretmen</NavLink>34 <NavLink onClick={() => setSelector(2)} className="dropdown-item" exact activeClassName="active" to="/report-homeworks">Ãdev</NavLink>35 <NavLink onClick={() => setSelector(2)} className="dropdown-item" exact activeClassName="active" to="/report-classes">Sınıf</NavLink>36 </div>37 </li>38 <li className="nav-item">39 <NavLink onClick={() => setSelector(0)} className="nav-link" to="/update-etudes" exact activeClassName="active">Birebir Kontrol</NavLink>40 </li>41 <li className="nav-item">42 <NavLink onClick={() => setSelector(0)} to="/update-homeworks" className="nav-link" exact activeClassName="active">Ãdev Kontrol</NavLink>43 </li>44 </ul>45 </div>46 <button type="button" className="btn btn-danger" onClick={() => { logOut() }}>47 ÃıkıŠYap48 </button>49 </nav>50 )51}...
head.js
Source:head.js
...15 const twitterUser = '@Sjeiti'16 //17 document.title = title+(title?' - ':'')+siteName18 //19 setSelector('link[rel="canonical"]', 'href', link)20 setSelector('meta[name="description"]', 'content', metaDescription)21 // Opengraph22 setSelector('meta[property="og:locale"]', 'content', 'en_US')23 setSelector('meta[property="og:type"]', 'content', 'article')24 setSelector('meta[property="og:title"]', 'content', title)25 setSelector('meta[property="og:description"]', 'content', metaDescription)26 setSelector('meta[property="og:url"]', 'content', link)27 setSelector('meta[property="og:site_name"]', 'content', siteName)28 setSelector('meta[property="og:updated_time"]', 'content', modified)29 setSelector('meta[property="og:image"]', 'content', image)30 image&&setSelector('meta[property="og:image:width"]', 'content', imageW)31 image&&setSelector('meta[property="og:image:height"]', 'content', imageH)32 // Facebook33 // setSelector('meta[property="article:tag"]','content','foo') // todo implement setSelector multiple34 // setSelector('meta[property="article:tag"]','content','foo') // todo implement setSelector multiple35 // setSelector('meta[property="article:section"]','content','foo') // todo implement setSelector multiple36 setSelector('meta[property="article:published_time"]', 'content', date)37 setSelector('meta[property="article:modified_time"]', 'content', modified)38 // Twitter39 setSelector('meta[property="twitter:card"]', 'content', 'summary')40 setSelector('meta[property="twitter:description"]', 'content', metaDescription)41 setSelector('meta[property="twitter:title"]', 'content', title)42 setSelector('meta[property="twitter:site"]', 'content', twitterUser)43 setSelector('meta[property="twitter:image"]', 'content', image)44 setSelector('meta[property="twitter:creator"]', 'content', twitterUser)45 // rss46 setSelector('link[rel="alternate"][href="https://ronvalstar.nl/feed.rss"]')47 //48 // robots49 const isNoIndex = /^search\//.test(slug)50 ||title==='404'51 ||date?.includes('9999') 52 ||dateFrom?.includes('9999') 53 if (isNoIndex){54 setSelector('meta[property="robots"]', 'content', 'noindex,follow')55 } else {56 const robots = document.querySelector('meta[property="robots"]')57 robots&&robots.parentNode.removeChild(robots)58 }59})60/**61 * Update or create an element/value62 * @param {string} selector63 * @param {string} key64 * @param {string} value65 * @todo: key/value could be superfluous66 */67function setSelector(selector, key, value){68 if (value){69 const elm = selectOrCreate(document.head, selector)70 key&&elm.setAttribute(key, value)71 } else {72 const elm = document.head.querySelector(selector)73 elm&&elm.parentNode.removeChild(elm)74 }75}76/**77 * Return or create an element78 * @param {HTMLElement} root79 * @param {string} selector80 * @returns {HTMLElement}81 */...
Selectors.js
Source:Selectors.js
...4 <div className="table-buttons">5 <div className="row">6 <button7 className={selectors.one ? "number-active" : ""}8 onClick={() => setSelector(1)}9 >10 111 </button>12 <button13 className={selectors.two ? "number-active" : ""}14 onClick={() => setSelector(2)}15 >16 217 </button>18 <button19 className={selectors.three ? "number-active" : ""}20 onClick={() => setSelector(3)}21 >22 323 </button>24 </div>25 <div className="row">26 <button27 className={selectors.four ? "number-active" : ""}28 onClick={() => setSelector(4)}29 >30 431 </button>32 <button33 className={selectors.five ? "number-active" : ""}34 onClick={() => setSelector(5)}35 >36 537 </button>38 <button39 className={selectors.six ? "number-active" : ""}40 onClick={() => setSelector(6)}41 >42 643 </button>44 </div>45 <div className="row">46 <button47 className={selectors.seven ? "number-active" : ""}48 onClick={() => setSelector(7)}49 >50 751 </button>52 <button53 className={selectors.eight ? "number-active" : ""}54 onClick={() => setSelector(8)}55 >56 857 </button>58 <button59 className={selectors.nine ? "number-active" : ""}60 onClick={() => setSelector(9)}61 >62 963 </button>64 </div>65 <div className="row">66 <button67 className={selectors.ten ? "number-active" : ""}68 onClick={() => setSelector(10)}69 >70 1071 </button>72 <button73 className={selectors.eleven ? "number-active" : ""}74 onClick={() => setSelector(11)}75 >76 1177 </button>78 <button79 className={selectors.twelve ? "number-active" : ""}80 onClick={() => setSelector(12)}81 >82 1283 </button>84 </div>85 </div>86 );87};...
Using AI Code Generation
1const { setSelectorEngine } = require('@playwright/test');2setSelectorEngine('css');3const { setSelectorEngine } = require('@playwright/test');4setSelectorEngine('xpath');5const { setSelectorEngine } = require('@playwright/test');6setSelectorEngine('text');7const { test } = require('@playwright/test');8test('my test', async ({ page }) => {9 await page.click('css=button >> css=span');10 await page.click('text=Click me');11});12const { test, expect } = require('@playwright/test');13test('basic test', async ({ page }) => {14 const title = page.locator('css=header >> css=div');15 await expect(title).toHaveText('Playwright');16});17const { chromium } = require('playwright');18(async () => {19 const browser = await chromium.launch();20 const page = await browser.newPage();21 await page.screenshot({ path: `example.png` });22 await browser.close();23})();
Using AI Code Generation
1const { setSelectorEngine } = require('@playwright/test/lib/server/selectors/selectorEngine');2const { XPathEngine } = require('@playwright/test/lib/server/selectors/xpathEngine');3setSelectorEngine(new XPathEngine());4const { select } = require('@playwright/test/lib/server/selectors/selectorEngine');5const { XPathEngine } = require('@playwright/test/lib/server/selectors/xpathEngine');6const { setSelectorEngine } = require('@playwright/test/lib/server/selectors/selectorEngine');7const { XPathEngine } = require('@playwright/test/lib/server/selectors/xpathEngine');8setSelectorEngine(new XPathEngine());9module.exports = {10 globalSetup: require.resolve('./globalSetup.js')11};12const { setSelectorEngine } = require('@playwright/test/lib/server/selectors/selectorEngine');13setSelectorEngine(null);14module.exports = {15 globalTeardown: require.resolve('./globalTeardown.js')16};17const { test, expect } = require('@playwright/test');18test('xpath', async ({ page }) => {19 const element = await page.waitForSelector(xpath);20 expect(element).toBeTruthy();21});
Using AI Code Generation
1const { setSelectorEngine } = require("@playwright/test/lib/server/selectors");2setSelectorEngine("css", require("playwright/lib/server/selectors/cssSelectorEngine"));3const { setSelectorEngine } = require("@playwright/test/lib/server/selectors");4setSelectorEngine("css", require("playwright/lib/server/selectors/cssSelectorEngine"));5const { test, expect } = require('@playwright/test');6test('My first test', async ({ page }) => {
Using AI Code Generation
1const {setSelectorEngine} = require('playwright/lib/internal/selectors/selectorEngine');2const {registerEngine} = require('playwright/lib/internal/selectors/selectorEngines');3const {SelectorEngine} = require('playwright/lib/internal/selectors/selectorEngine');4const {Selector} = require('playwright/lib/internal/selectors/selector');5const {ElementHandle} = require('playwright/lib/internal/elementHandle');6registerEngine('test', (selector, _root) => {7 return function (element) {8 return element.getAttribute('data-test');9 };10});11setSelectorEngine('test');12const selector = new Selector('test');13const elementHandle = new ElementHandle();14const result = selector.evaluate(elementHandle);15console.log(result);16const {setSelectorEngine} = require('playwright/lib/internal/selectors/selectorEngine');17const {registerEngine} = require('playwright/lib/internal/selectors/selectorEngines');18const {SelectorEngine} = require('playwright/lib/internal/selectors/selectorEngine');19const {Selector} = require('playwright/lib/internal/selectors/selector');20const {ElementHandle} = require('playwright/lib/internal/elementHandle');21registerEngine('test', (selector, _root) => {22 return function (element) {23 return element.getAttribute('data-test');24 };25});
Using AI Code Generation
1const { setSelectorEngine } = require('@playwright/test');2const { SelectorEngine } = require('playwright-selector-engine');3setSelectorEngine(SelectorEngine);4const { Selector } = require('@playwright/test');5const selector = Selector('button').withText('Click Me');6const { Selector } = require('@playwright/test');7const selector = Selector('button').withText('Click Me');8const element = await selector();9const { Selector } = require('@playwright/test');10const selector = Selector('button').withText('Click Me');11const text = await selector.innerText();12const { Selector } = require('@playwright/test');13const selector = Selector('button').withText('Click Me');14const attribute = await selector.getAttribute('type');15const { Selector } = require('@playwright/test');16const selector = Selector('button').withText('Click Me');17const count = await selector.count();18const { Selector } = require('@playwright/test');19const selector = Selector('button').withText('Click Me');20const exists = await selector.exists();21const { Selector } = require('@playwright/test');22const selector = Selector('button').withText('Click Me');23const visible = await selector.isVisible();24const { Selector } = require('@playwright/test');25const selector = Selector('button').withText('Click Me');26const enabled = await selector.isEnabled();
Using AI Code Generation
1const playwright = require('playwright');2const { SelectorEngine } = require('playwright/lib/internal/selectorEngine');3const { helper } = require('playwright/lib/helper');4const { selectors } = require('playwright/lib/selectors');5const { Selector } = require('playwright/lib/selectors/selector');6const { Selectors } = require('playwright/lib/selectors/selectors');7const { SelectorEvaluator } = require('playwright/lib/selectors/selectorEvaluator');8const { SelectorList } = require('playwright/lib/selectors/selectorList');9const { SelectorPlaywright } = require('playwright/lib/selectors/selectorPlaywright');10const { SelectorTimeoutError } = require('playwright/lib/selectors/selectorTimeoutError');11const { SelectorEngineHandle } = require('playwright/lib/selectors/selectorEngineHandle');12const { SelectorEngineHandleImpl } = require('playwright/lib/selectors/selectorEngineHandleImpl');13const { SelectorEngineHandleJS } = require('playwright/lib/selectors/selectorEngineHandleJS');14const { SelectorEngineHandleJSHandle } = require('playwright/lib/selectors/selectorEngineHandleJSHandle');15const { SelectorEngineHandleText } = require('playwright/lib/selectors/selectorEngineHandleText');16const { SelectorEngineHandleElement } = require('playwright/lib/selectors/selectorEngineHandleElement');17const { SelectorEngineHandleElementHandle } = require('playwright/lib/selectors/selectorEngineHandleElementHandle');18const { SelectorEngineHandleElementHandleImpl } = require('playwright/lib/selectors/selectorEngineHandleElementHandleImpl');19const { SelectorEngineHandleElementHandleJSHandle } = require('playwright/lib/selectors/selectorEngineHandleElementHandleJSHandle');20const { SelectorEngineHandleElementHandleJSHandleImpl } = require('playwright/lib/selectors/
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!!