Best JavaScript code snippet using playwright-internal
VersionTagParticipantSpec.js
Source:VersionTagParticipantSpec.js
1'use strict';2var TestHelper = require('../../../TestHelper');3var TestContainer = require('mocha-test-container-support');4/* global bootstrapModeler, inject */5var propertiesPanelModule = require('lib'),6 domQuery = require('min-dom').query,7 coreModule = require('bpmn-js/lib/core').default,8 selectionModule = require('diagram-js/lib/features/selection').default,9 modelingModule = require('bpmn-js/lib/features/modeling').default,10 propertiesProviderModule = require('lib/provider/camunda'),11 camundaModdlePackage = require('camunda-bpmn-moddle/resources/camunda'),12 getBusinessObject = require('bpmn-js/lib/util/ModelUtil').getBusinessObject;13describe('Version-Tag', function() {14 var diagramXML = require('./VersionTagParticipant.bpmn');15 var testModules = [16 coreModule, selectionModule, modelingModule,17 propertiesPanelModule,18 propertiesProviderModule19 ];20 var container;21 beforeEach(function() {22 container = TestContainer.get(this);23 });24 beforeEach(bootstrapModeler(diagramXML, {25 modules : testModules,26 moddleExtensions : { camunda : camundaModdlePackage }27 }));28 beforeEach(inject(function(commandStack, propertiesPanel) {29 var undoButton = document.createElement('button');30 undoButton.textContent = 'UNDO';31 undoButton.addEventListener('click', function() {32 commandStack.undo();33 });34 container.appendChild(undoButton);35 propertiesPanel.attachTo(container);36 }));37 it('should add attribute when not empty on processRef', inject(function(propertiesPanel, selection, elementRegistry) {38 var shape = elementRegistry.get('Participant_2'),39 inputEl = 'input[name=versionTag]';40 // given41 selection.select(shape);42 var bo = getBusinessObject(shape).get('processRef'),43 inputElement = domQuery(inputEl, propertiesPanel._container);44 TestHelper.triggerValue(inputElement, '', 'change');45 // when46 TestHelper.triggerValue(inputElement, '1.0.2', 'change');47 // then48 expect(bo.get('camunda:versionTag')).to.equal('1.0.2');49 }));50 it('should fetch the value of the attribute on processRef', inject(function(propertiesPanel, selection, elementRegistry) {51 // given52 var shape = elementRegistry.get('Participant_1');53 // when54 selection.select(shape);55 var bo = getBusinessObject(shape).get('processRef');56 // then57 expect(bo.get('camunda:versionTag')).to.equal('1.0.0');58 }));59 it('should modify the value of the attribute on processRef', inject(function(propertiesPanel, selection, elementRegistry) {60 var shape = elementRegistry.get('Participant_1'),61 inputEl = 'input[name=versionTag]';62 // given63 selection.select(shape);64 var bo = getBusinessObject(shape).get('processRef'),65 inputElement = domQuery(inputEl, propertiesPanel._container);66 // when67 TestHelper.triggerValue(inputElement, '1.0.2', 'change');68 // then69 expect(bo.get('camunda:versionTag')).to.equal('1.0.2');70 }));71 it('should remove attribute from processRef when value is empty', inject(function(propertiesPanel, selection, elementRegistry) {72 var shape = elementRegistry.get('Participant_1'),73 inputEl = 'input[name=versionTag]';74 // given75 selection.select(shape);76 var bo = getBusinessObject(shape).get('processRef'),77 inputElement = domQuery(inputEl, propertiesPanel._container);78 // when79 TestHelper.triggerValue(inputElement, '', 'change');80 // then81 expect(bo.get('camunda:versionTag')).to.be.undefined;82 }));83 it('should add attribute to processRef when the remove is undone', inject(function(propertiesPanel, selection, elementRegistry, commandStack) {84 var shape = elementRegistry.get('Participant_1'),85 inputEl = 'input[name=versionTag]';86 selection.select(shape);87 var bo = getBusinessObject(shape).get('processRef'),88 inputElement = domQuery(inputEl, propertiesPanel._container);89 // given90 TestHelper.triggerValue(inputElement, '', 'change');91 // when92 commandStack.undo();93 var versionTagField = bo.get('camunda:versionTag');94 // then95 expect(versionTagField).not.to.be.undefined;96 expect(versionTagField).to.equal('1.0.0');97 }));...
command.js
Source:command.js
1/**2 * Wrapper to the node-cmd library3 * @private4 */5var cmd = require('node-cmd');6var config = require('journal.io.config.json');7var eventsCount = 0;8var utils = require('./utils');9var log = utils.log;10/**11 * Default timeout (in milliseconds) for which a command lasts for.12 * @constant13 */14const DEFAULT_TIMEOUT = 10000;15let _timeout = config.timeout ? config.timeout : DEFAULT_TIMEOUT;16let getTimeout = () => _timeout == -1 ? undefined : _timeout;17let setTimeout = (t) => _timeout = t;18//If ignore lines = True means the command will not stop when terminal reaches more than _lines (meaning max lines). TODO: Consider just replacing by a single variable?19let _ignoreLines = false;20let _lines = 10;21let getLines = () => _lines;22let setLines = (n) => _lines = n;23exports.logToFile = (preffix = 'Commands') => log = utils.fileLogger(preffix); 24exports.setTimeout = (t) => setTimeout(t);25exports.setLines = (n) => setLines(n);26exports.ignoreLines = (b) => _ignoreLines = b;27exports.do = (command, callback, from = 0, lines = getLines(), timeout = getTimeout()) => {28 log.debug(`Called function with args: "${command}, ${callback}, ${from}, ${lines}, ${timeout}"`);29 let processRef = cmd.get(command, (err, _, stderr) => {30 if(err) {31 log.error(stderr);32 }33 });34 let data_line = "";35 let index = 0;36 //listen to the terminal output37 let _event = ('data', (data) => {38 log.debug(`Received data from output: ${data}...`);39 if (!_ignoreLines && lines <= 0) {40 eventsCount--;41 log.warn(`Limit of lines expired, ignoring data from terminal and removing event (count = ${eventsCount})...`);42 processRef.stdout.removeListener('data', _event);43 return;44 }45 index++;46 log.debug(`'index' was increased to ${index}...`);47 if(index <= from) return;48 data_line += data;49 if (data_line[data_line.length-1] == '\n') {50 log.debug('Received all the data from this line');51 lines--;52 index++;53 if(index <= from) return; 54 //Make sure we really copy the original string and not a reference of it55 let dataToSend = '' + data_line;56 data_line = ""; //We don't need it anymore57 log.debug(`Sending final data to callback: '${dataToSend}'`);58 callback(dataToSend);59 }60 });61 processRef.stdout.on('data', _event);62 processRef.timedOut = false;63 //Set event timeout64 if(timeout) {65 setTimeout(() => {66 try {67 log.info(`Removing event due to timeout...`);68 processRef.timedOut = true;69 processRef.stdout.removeListener('data', _event);70 processRef.kill();71 eventsCount--; 72 } catch(e) {73 log.error(`Exception happened while trying to remove event listener and killed process reference ${processRef.pid}: ${e.message}`);74 log.error(e);75 }76 }, timeout);77 }78 eventsCount++;79 return processRef;...
participant.js
Source:participant.js
1/**2 *3 * ©2016-2017 EdgeVerve Systems Limited (a fully owned Infosys subsidiary),4 * Bangalore, India. All Rights Reserved.5 *6 */7'use strict';8var logger = require('oe-logger');9var log = logger('Participant-Parser');10/**11 * Create a bpmn participant12 * @param {String} bpmnId BpmnId13 * @param {String} name Name14 * @param {String} type Type15 * @param {String} processRef ProcessRef16 * @constructor17 */18function BPMNParticipant(bpmnId, name, type, processRef) {19 log.debug(log.defaultContext(), 'BPMNParticipant called');20 this.bpmnId = bpmnId;21 this.name = name;22 this.type = type;23 this.processRef = processRef;24}25/**26 * create an array of all participants in a collaboration definition27 * @param {Object} defObject An array of participants in a collaboration entity28 * @constructor29 */30exports.createBPMNParticipant = function createBPMNParticipant(defObject) {31 var participants = [];32 var bpmnId;33 var name;34 var processRef;35 var type;36 var finalParticipant;37 var participant;38 if (typeof defObject !== 'undefined' && defObject.constructor.name === 'Array') {39 for (participant of defObject) {40 name = '';41 bpmnId = '';42 processRef = null;43 if (participant.hasOwnProperty('attributes_')) {44 if (participant.attributes_.hasOwnProperty('id')) {45 bpmnId = participant.attributes_.id.value;46 }47 if (participant.attributes_.hasOwnProperty('name')) {48 name = participant.attributes_.name.value;49 }50 if (participant.attributes_.hasOwnProperty('processRef')) {51 processRef = participant.attributes_.processRef.value;52 }53 }54 if (participant.hasOwnProperty('attributes_ns')) {55 type = participant.attributes_ns.local;56 }57 finalParticipant = new BPMNParticipant(bpmnId, name, type, processRef);58 participants.push(finalParticipant);59 }60 }61 if (defObject.constructor.name === 'Object') {62 participant = defObject;63 if (participant.hasOwnProperty('attributes_')) {64 if (participant.attributes_.hasOwnProperty('id')) {65 bpmnId = participant.attributes_.id.value;66 }67 if (participant.attributes_.hasOwnProperty('name')) {68 name = participant.attributes_.name.value;69 }70 if (participant.attributes_.hasOwnProperty('processRef')) {71 processRef = participant.attributes_.processRef.value;72 }73 }74 if (participant.hasOwnProperty('attributes_ns')) {75 type = participant.attributes_ns.local;76 }77 finalParticipant = new BPMNParticipant(bpmnId, name, type, processRef);78 participants.push(finalParticipant);79 }80 return participants;...
messenger.mjs
Source:messenger.mjs
1'use strict';2import { Worker } from 'cluster';3import { ChildProcess } from 'child_process';4import sleeper from './sleeper.mjs';5import { TIME_UNIT } from './constants.mjs';6const TIMEOUT = 0.2;7const messenger = (processRef) => {8 let _reject = null;9 let _resolve = null;10 const listener = (message) => _resolve(message);11 let targetProcess;12 if (processRef instanceof Worker || processRef instanceof ChildProcess) {13 targetProcess = processRef;14 } else if (typeof process.send === 'function') {15 targetProcess = process;16 } else if (typeof process.emit === 'function') {17 targetProcess = process;18 targetProcess.send = (message) => targetProcess.emit('message', message);19 } else {20 throw new TypeError('processRef should be either a Worker or a ChildProcess');21 }22 return {23 receive: new Promise((resolve, reject) => {24 _reject = reject;25 _resolve = resolve;26 targetProcess.once('message', listener);27 }),28 send: (message) => targetProcess.send(message),29 interrupt: () => {30 targetProcess.removeListener('message', listener);31 _reject('interrupted');32 }33 };34};35/**36 * Promise to emulate request - response for messages between (cluster) members37 * @param { Object } message38 * @param { Worker | ChildProcess } processRef39 * @param { Number } waitTime40 * @param { Number } timeUnit41 */42export default (message, processRef = null, waitTime = TIMEOUT, timeUnit = TIME_UNIT.SECOND) =>43 new Promise((resolve, reject) => {44 if (typeof message !== 'object') {45 return Promise.reject(new TypeError('message should be an object'));46 }47 if (processRef !== null && !(processRef instanceof Worker ||48 processRef instanceof ChildProcess)) {49 return Promise.reject(new TypeError('processRef should be a Worker or ChildProcess'));50 }51 if (typeof waitTime !== 'number') {52 return Promise.reject(new TypeError('waitTime should be a number'));53 }54 if (!(timeUnit in Object.values(TIME_UNIT))) {55 return Promise.reject(new TypeError('timeUnit should be in timeUnitEnum'));56 }57 const { sleep, interrupt : wakeUp } = sleeper(waitTime, timeUnit, true);58 const { send, receive, interrupt : tooLate } = messenger(processRef);59 Promise.allSettled([60 Promise.race([sleep, receive]),61 Promise.resolve(send(message))62 ]).then((results) => {63 const { status : s0, value : v0 } = results[0];64 if (s0 === 'fulfilled') {65 wakeUp();66 resolve(v0);67 } else {68 tooLate();69 reject(new Error('no response message (messenger)'));70 }71 });...
DocumentationProps.js
Source:DocumentationProps.js
1'use strict';2var entryFactory = require('../../../factory/EntryFactory'),3 cmdHelper = require('../../../helper/CmdHelper');4var ModelUtil = require('bpmn-js/lib/util/ModelUtil'),5 is = ModelUtil.is,6 getBusinessObject = ModelUtil.getBusinessObject;7module.exports = function(group, element, bpmnFactory, translate) {8 var getValue = function(businessObject) {9 return function(element) {10 var documentations = businessObject && businessObject.get('documentation'),11 text = (documentations && documentations.length > 0) ? documentations[0].text : '';12 return { documentation: text };13 };14 };15 var setValue = function(businessObject) {16 return function(element, values) {17 var newObjectList = [];18 if (typeof values.documentation !== 'undefined' && values.documentation !== '') {19 newObjectList.push(bpmnFactory.create('bpmn:Documentation', {20 text: values.documentation21 }));22 }23 return cmdHelper.setList(element, businessObject, 'documentation', newObjectList);24 };25 };26 // Element Documentation27 var elementDocuEntry = entryFactory.textBox({28 id: 'documentation',29 label: translate('Element Documentation'),30 modelProperty: 'documentation'31 });32 elementDocuEntry.set = setValue(getBusinessObject(element));33 elementDocuEntry.get = getValue(getBusinessObject(element));34 group.entries.push(elementDocuEntry);35 var processRef;36 // Process Documentation when having a Collaboration Diagram37 if (is(element, 'bpmn:Participant')) {38 processRef = getBusinessObject(element).processRef;39 // do not show for collapsed Pools/Participants40 if (processRef) {41 var processDocuEntry = entryFactory.textBox({42 id: 'process-documentation',43 label: translate('Process Documentation'),44 modelProperty: 'documentation'45 });46 processDocuEntry.set = setValue(processRef);47 processDocuEntry.get = getValue(processRef);48 group.entries.push(processDocuEntry);49 }50 }...
vaultLoader.js
Source:vaultLoader.js
1'use strict';2const child_process = require('child_process');3function pKiller(processRef) {4 return new Promise(function (resolve, reject) {5 processRef.on('exit', (/*code, signal*/) => {6 //console.log('child process terminated due to receipt of signal '+signal);7 resolve();8 });9 processRef.on('error', err => {10 reject(err);11 });12 processRef.kill();13 });14}15module.exports = function () {16 return new Promise(function (resolve, reject) {17 const processRef = child_process.spawn('/usr/local/bin/vault', ['server', '-dev']);18 let dataAcc = '';19 processRef.stdout.on('data', function(data) {20 if (dataAcc === null) {21 return;22 }23 dataAcc += data.toString(); //we receive binary data here24 const found = dataAcc.match(/Root Token: ([a-z0-9\-]+)\n/i);25 if (found !== null) {26 dataAcc = null;27 resolve({28 rootToken: found[1],29 kill: () => pKiller(processRef),30 });31 }32 });33 processRef.on('error', err => {34 reject(err);35 });36 });...
processtaskdefinition.js
Source:processtaskdefinition.js
1class ProcessTaskDefinition extends TaskDefinition {2 static get prefix() {3 return 'pt';4 }5 constructor(importNode, caseDefinition, parent) {6 super(importNode, caseDefinition, parent);7 this.processRef = this.parseAttribute('processRef');8 }9 createExportNode(parentNode) {10 super.createExportNode(parentNode, 'processTask', 'processRef', 'mappings');11 }12 get implementationRef() {13 return this.processRef;14 }15 set implementationRef(ref) {16 this.processRef = ref;17 }...
node-py.js
Source:node-py.js
1const cmd=require('node-cmd');2 3const processRef=cmd.run('python -i');4let data_line = '';5 6//listen to the python terminal output7processRef.stdout.on(8 'data',9 function(data) {10 data_line += data;11 if (data_line[data_line.length-1] == '\n') {12 console.log(data_line);13 }14 }15);16 17const pythonTerminalInput=`primes = [2, 3, 5, 7]18for prime in primes:19 print(prime)20 21`;22 23//show what we are doing24console.log(`>>>${pythonTerminalInput}`);25 26//send it to the open python terminal27processRef.stdin.write(pythonTerminalInput);...
Using AI Code Generation
1const { chromium } = require('playwright');2(async () => {3 const browser = await chromium.launch();4 const context = await browser.newContext();5 const page = await context.newPage();6 const element = await page.$('input');7 const handle = await element.asElement();
Using AI Code Generation
1const { chromium } = require('playwright');2(async () => {3 const browser = await chromium.launch();4 const context = await browser.newContext();5 const page = await context.newPage();6 const ref = await page.evaluateHandle(() => document);7 const processRef = require('playwright/lib/server/supplements/recorder/recorderApp').processRef;8 const result = await processRef(ref);9 console.log(result);10 await browser.close();11})();12{ type: 'node',13 objectId: '{"injectedScriptId":1,"id":1}' }
Using AI Code Generation
1const { chromium } = require('playwright');2const { processRef } = require('playwright/lib/server/dom.js');3(async () => {4 const browser = await chromium.launch();5 const context = await browser.newContext();6 const page = await context.newPage();7 const elementHandle = await page.$('body');8 const element = await elementHandle.evaluateHandle(node => processRef(node));9 console.log(element);10 await browser.close();11})();12ElementHandle {13 _context: BrowserContext {14 _options: { viewport: null, ignoreHTTPSErrors: false, javaScriptEnabled: true, bypassCSP: false, userAgent: null, locale: null, timezoneId: null, geolocation: null, permissions: [], extraHTTPHeaders: null, offline: false, httpCredentials: null, deviceScaleFactor: null, isMobile: false, hasTouch: false, colorScheme: null, acceptDownloads: false, _recordHarPath: null, _recordHarOmitContent: false, _recordVideoDir: null, _recordVideoSize: null, _screenshotDir: null, _screenshotPath: null, _timeoutSettings: TimeoutSettings {}, _logger: Logger { _name: 'pw:browser' }, _browserOptions: [Object], _browserType: [Object], _browser: [Object], _defaultContext: [Circular] },15 _browser: Browser {16 },17 _browserType: BrowserType {18 _executablePath: 'C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe',19 _timeoutSettings: TimeoutSettings { _timeout: 30000, _defaultTimeout: 30000 },20 _logger: Logger { _name: 'pw:browserType' },
Using AI Code Generation
1const { chromium } = require("playwright");2const { processRef } = require("playwright/lib/server/frames");3(async () => {4 const browser = await chromium.launch();5 const context = await browser.newContext();6 const page = await context.newPage();7 const element = await page.$("input[name=q]");8 const ref = await processRef(element);9 console.log("ref", ref);10 await browser.close();11})();12ref {13 customPreview: {14 {15 },16 {17 },18 {19 },20 {21 },22 {23 },24 {25 }26 }27}28const { chromium } = require("playwright");29const { processRef } = require("playwright/lib/server/frames");30(async () => {31 const browser = await chromium.launch();32 const context = await browser.newContext();33 const page = await context.newPage();34 const element = await page.$("input[name=q]");35 const ref = await processRef(element);36 console.log("ref", ref);37 await page.evaluate((ref) => {38 ref.click();
Using AI Code Generation
1const { processRef } = require('playwright/lib/server/dom.js');2const { createTestServer } = require('playwright/lib/utils/testserver/');3const { chromium } = require('playwright');4(async () => {5 const server = await createTestServer();6 server.setRoute('/test.html', (req, res) => {7 res.end(`8 `);9 });10 const browser = await chromium.launch();11 const context = await browser.newContext();12 const page = await context.newPage();13 await page.goto(server.PREFIX + '/test.html');14 const divHandle = await page.$('#mydiv');15 const divRef = await divHandle._remoteObject.objectId;16 const element = await processRef(divRef, page);17 const text = await page.evaluate(element => element.textContent, element);18 await browser.close();19 await server.stop();20})();21const { serializeResult } = require('./serializer');22const { assert } = require('../utils/utils');23async function processRef(ref, page) {24 const { objectId } = ref;25 assert(objectId, 'objectId is not defined');26 const { result, exceptionDetails } = await page._delegate.send('Runtime.callFunctionOn', {27 functionDeclaration: `function() {28 return this;29 }`,30 });31 if (exceptionDetails)32 throw new Error('Exception thrown in page: ' + serializeResult(exceptionDetails));33 return result;34}35function serializeResult(result) {36 if (result.type === 'object') {37 if (result.subtype === 'node') {38 return {39 value: {40 nodeType: result.description.split(' ')[0],41 nodeName: result.description.split(' ')[1],
Using AI Code Generation
1const { Internal } = require("playwright-core/lib/server/instrumentation");2const { BrowserContext } = require("playwright-core/lib/server/chromium/browserContext");3const { Browser } = require("playwright-core/lib/server/chromium/browser");4const { Page } = require("playwright-core/lib/server/chromium/page");5const { Frame } = require("playwright-core/lib/server/chromium/frame");6const { ElementHandle } = require("playwright-core/lib/server/chromium/elementHandler");7const { JSHandle } = require("playwright-core/lib/server/chromium/jsHandle");8const internal = new Internal();9const context = new BrowserContext(internal, browser, "context1", {});10const elementHandle = new ElementHandle(internal, frame, "elementHandle1", {});11const jsHandle = new JSHandle(internal, frame, "jsHandle1", {});12const ref = internal.processRef(browser);13const ref = internal.processRef(context);14const ref = internal.processRef(page);15const ref = internal.processRef(frame);16const ref = internal.processRef(elementHandle);17const ref = internal.processRef(jsHandle);
Using AI Code Generation
1const { InternalAPI } = require('playwright');2const { test, expect } = require('@playwright/test');3test.describe('test', () => {4 test('test', async ({ page }) => {5 const processRef = await InternalAPI.getProcessRef(page);6 console.log('processRef', processRef);7 });8});
Using AI Code Generation
1const { processRef } = require('playwright/lib/internal/evaluators/JavaScriptAction');2const { Page } = require('playwright');3const page = new Page();4const selector = 'div';5const ref = page.$(selector);6const result = processRef(ref);7console.log(result);8{ element: ElementHandle { page: Page, context: BrowserContext, selector: 'div' } }9const { processRef } = require('playwright/lib/internal/evaluators/JavaScriptAction');10const { Page } = require('playwright');11const page = new Page();12const selector = 'div';13const ref = page.$(selector);14const result = processRef(ref);15console.log(result);16page.on('click', async () => {17 const elementHandle = await page.evaluateHandle(() => document.activeElement);18});19{ element: ElementHandle { page: Page, context: BrowserContext, selector: 'div' } }20const { processRef } = require('playwright/lib/internal/evaluators/JavaScriptAction');21const { Page } = require('playwright');22const page = new Page();23const selector = 'div';24const ref = page.$(selector);25const result = processRef(ref);26console.log(result);27page.on('click', async () => {28 const elementHandle = await result.evaluateHandle(() => document.activeElement);29});30{ element: ElementHandle { page: Page, context: BrowserContext, selector: 'div' } }
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!!