Best JavaScript code snippet using playwright-internal
InspectorFrontendHost.js
Source:InspectorFrontendHost.js
...535/**536 * @param {!Object<string, string>=} prefs537 * @return {boolean}538 */539export function isUnderTest(prefs) {540 // Integration tests rely on test queryParam.541 if (Root.Runtime.queryParam('test')) {542 return true;543 }544 // Browser tests rely on prefs.545 if (prefs) {546 return prefs['isUnderTest'] === 'true';547 }548 return Common.settings && Common.settings.createSetting('isUnderTest', false).get();549}550/* Legacy exported object */551self.Host = self.Host || {};552/* Legacy exported object */553Host = Host || {};...
ServiceManager.js
Source:ServiceManager.js
...29 createAppService(appName, serviceName) {30 let url = appName + '.js';31 const remoteBase = Runtime.queryParam('remoteBase');32 const debugFrontend = Runtime.queryParam('debugFrontend');33 const isUnderTest = Host.isUnderTest();34 const queryParams = [];35 if (remoteBase)36 queryParams.push('remoteBase=' + remoteBase);37 if (debugFrontend)38 queryParams.push('debugFrontend=' + debugFrontend);39 if (isUnderTest)40 queryParams.push('isUnderTest=true');41 if (queryParams.length)42 url += `?${queryParams.join('&')}`;43 const worker = new Worker(url);44 const connection = new Services.ServiceManager.Connection(new Services.ServiceManager.WorkerServicePort(worker));45 return connection._createService(serviceName);46 }47};...
examTestFormat.js
Source:examTestFormat.js
1import { LightningElement, wire, track } from 'lwc';2import { ShowToastEvent } from 'lightning/platformShowToastEvent';3import getExistExam from '@salesforce/apex/ExamTestFormatController.getExistExam';4import geteqQuestions from '@salesforce/apex/ExamTestFormatController.geteqQuestions';5import geteqAnswers from '@salesforce/apex/ExamTestFormatController.geteqAnswers';6import countExistExam from '@salesforce/apex/ExamTestFormatController.countExistExam';7import { refreshApex } from '@salesforce/apex';8const columns = [9 {label : '解ç', fieldName : 'Answer__c'},10];11export default class examTestFormat extends LightningElement {12 @track existExam;13 @track selectedExam;14 @track examdatas = [];15 @track columns = columns;16 @track isUnderTest = false;17 examtemp = [];18 @track dispExam;19 examnumber = 0;20 selectedanswer;21 @track dispnum = 1;22 @track totalnum;23 @track progressnum = 0;24 @track selectedRows = [];25 @track isMark = false;26 @track isResult = false;27 @track passedNum = 0;28 @track passedPer = 0;29 @track isDrawing = false;30 @track wireExam;31 nextId;32 examslidenumber = 10;33 @track examresult = [];34 existExamCnt;35 @wire(countExistExam, {examname: '$selectedExam'})36 wirecountExistExam(result) {37 this.existExamCnt = result;38 if(result.data) {39 this.totalnum = result.data.length;40 }41 }42 connectedCallback() {43 getExistExam()44 .then(result => {45 this.existExam = [];46 result.forEach(element => {47 this.existExam.push({label: element.ExamType__c, value: element.ExamType__c});48 });49 if(this.existExam.length === 1) this.isMark = true;50 });51 }52 handleChange(e) {53 try{54 this.selectedExam = e.detail.value;55 return refreshApex(this.existExamCnt);56 }catch(exception) {57 58 }59 }60 async startExamFormat() {61 this.examtemp = await geteqQuestions({'examname': this.selectedExam});62 this.examdatas = [];63 this.passedNum = 0;64 this.passedPer = 0;65 this.examnumber = 0;66 this.progressnum = 0;67 this.dispnum = 1;68 this.isMark = false;69 this.selectedExam = undefined;70 this.examresult = [];71 72 const shuffle = ([...array]) => {73 for (let i = array.length - 1; i >= 0; i--) {74 const j = Math.floor(Math.random() * (i + 1));75 [array[i], array[j]] = [array[j], array[i]];76 }77 return array;78 }79 let temp = shuffle(this.examtemp);80 temp.forEach(element => {81 geteqAnswers({'Id': element.Id})82 .then(result => {83 let answer = result.filter(ans => {return ans.isAnswer__c === true});84 this.examdatas.push({exam: element, selection: shuffle(result), answers: answer});85 this.progressnum = Math.floor(100 / this.examslidenumber);86 this.dispExam = this.examdatas[this.examnumber];87 });88 this.isUnderTest = true;89 });90 }91 handleNext() {92 try{93 this.isDrawing = true;94 95 this.examdatas[this.examnumber]['selected'] = this.selectedanswer;96 this.examnumber ++;97 this.dispnum = this.examnumber + 1;98 if(this.dispnum == this.examslidenumber) {99 this.isMark = true;100 }101 this.progressnum = Math.floor((100 / this.examslidenumber) * this.dispnum);102 this.dispExam = this.examdatas[this.examnumber];103 this.isDrawing = false;104 this.nextId = this.dispExam.exam.Id;105 this.selectedRows = [];106 } catch(exception) {107 }108 }109 handlePrevious() {110 if(this.examnumber !== 0) {111 this.examnumber --;112 this.dispExam = this.examdatas[this.examnumber];113 }114 }115 116 handleRowAction(event) {117 this.selectedanswer = event.detail.selectedRows;118 }119 120 handleMark() {121 this.examdatas[this.examnumber]['selected'] = this.selectedanswer; 122 this.examdatas.forEach(element => {123 if(element.selected !== undefined){124 let isPassed = false;125 if(element.answers.length === element.selected.length) {126 isPassed = element.selected.every(item => {127 return item.isAnswer__c === true;128 });129 }130 element['isPassed'] = isPassed;131 if(isPassed === true){132 this.passedNum ++;133 }134 this.examresult.push(element);135 }136 });137 this.passedPer = Math.floor(this.passedNum / this.dispnum * 100);138 this.isResult = true;139 console.log('this.isResult: ' + this.isResult);140 }141 handleSliderChange(event) {142 this.examslidenumber = event.target.value;143 }144 gotoTop() {145 this.isResult = false;146 this.isUnderTest = false;147 }...
traceViewer.js
Source:traceViewer.js
1"use strict";2Object.defineProperty(exports, "__esModule", {3 value: true4});5exports.showTraceViewer = showTraceViewer;6var _path = _interopRequireDefault(require("path"));7var _fs = _interopRequireDefault(require("fs"));8var consoleApiSource = _interopRequireWildcard(require("../../../generated/consoleApiSource"));9var _httpServer = require("../../../utils/httpServer");10var _registry = require("../../../utils/registry");11var _utils = require("../../../utils/utils");12var _crApp = require("../../chromium/crApp");13var _instrumentation = require("../../instrumentation");14var _playwright = require("../../playwright");15var _progress = require("../../progress");16function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }17function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }18function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }19/**20 * Copyright (c) Microsoft Corporation.21 *22 * Licensed under the Apache License, Version 2.0 (the "License");23 * you may not use this file except in compliance with the License.24 * You may obtain a copy of the License at25 *26 * http://www.apache.org/licenses/LICENSE-2.027 *28 * Unless required by applicable law or agreed to in writing, software29 * distributed under the License is distributed on an "AS IS" BASIS,30 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.31 * See the License for the specific language governing permissions and32 * limitations under the License.33 */34async function showTraceViewer(traceUrls, browserName, headless = false, port) {35 for (const traceUrl of traceUrls) {36 if (!traceUrl.startsWith('http://') && !traceUrl.startsWith('https://') && !_fs.default.existsSync(traceUrl)) {37 // eslint-disable-next-line no-console38 console.error(`Trace file ${traceUrl} does not exist!`);39 process.exit(1);40 }41 }42 const server = new _httpServer.HttpServer();43 server.routePrefix('/trace', (request, response) => {44 const url = new URL('http://localhost' + request.url);45 const relativePath = url.pathname.slice('/trace'.length);46 if (relativePath.startsWith('/file')) {47 try {48 return server.serveFile(request, response, url.searchParams.get('path'));49 } catch (e) {50 return false;51 }52 }53 const absolutePath = _path.default.join(__dirname, '..', '..', '..', 'webpack', 'traceViewer', ...relativePath.split('/'));54 return server.serveFile(request, response, absolutePath);55 });56 const urlPrefix = await server.start(port);57 const traceViewerPlaywright = (0, _playwright.createPlaywright)('javascript', true);58 const traceViewerBrowser = (0, _utils.isUnderTest)() ? 'chromium' : browserName;59 const args = traceViewerBrowser === 'chromium' ? ['--app=data:text/html,', '--window-size=1280,800', '--test-type='] : [];60 if ((0, _utils.isUnderTest)()) args.push(`--remote-debugging-port=0`);61 const context = await traceViewerPlaywright[traceViewerBrowser].launchPersistentContext((0, _instrumentation.internalCallMetadata)(), '', {62 // TODO: store language in the trace.63 channel: (0, _registry.findChromiumChannel)(traceViewerPlaywright.options.sdkLanguage),64 args,65 noDefaultViewport: true,66 ignoreDefaultArgs: ['--enable-automation'],67 headless,68 useWebSocket: (0, _utils.isUnderTest)()69 });70 const controller = new _progress.ProgressController((0, _instrumentation.internalCallMetadata)(), context._browser);71 await controller.run(async progress => {72 await context._browser._defaultContext._loadDefaultContextAsIs(progress);73 });74 await context.extendInjectedScript(consoleApiSource.source);75 const [page] = context.pages();76 if (traceViewerBrowser === 'chromium') await (0, _crApp.installAppIcon)(page);77 if ((0, _utils.isUnderTest)()) page.on('close', () => context.close((0, _instrumentation.internalCallMetadata)()).catch(() => {}));else page.on('close', () => process.exit());78 const searchQuery = traceUrls.length ? '?' + traceUrls.map(t => `trace=${t}`).join('&') : '';79 await page.mainFrame().goto((0, _instrumentation.internalCallMetadata)(), urlPrefix + `/trace/index.html${searchQuery}`);80 return context;...
editor-display-controller.js
Source:editor-display-controller.js
1"use strict";2var _ = require('underscore'),3 EventEmitter = require('events').EventEmitter,4 application = require('../app/turo-application'),5 output = require('../app/to-editable-html'),6 buttons = require('./button-lookups'),7 isUnderTest = false,8 testPadding;9/***************************************************************/10var stringTimes = function (string, times) {11 var s = "";12 for (var i=0; i<times; i++) {13 s += string;14 }15 return s;16};17/***************************************************************/18var EditorController = function EditorController($native) {19 if ($native) {20 this.onLoad($native);21 }22 this._numberDisplayPrefs = {23 useUnitRefactor: true,24 index: 0,25 };26};27EditorController.prototype = new EventEmitter();28_.extend(EditorController.prototype, {29 onLoad: function ($native) {30 this.$native = $native;31 this.editor = application.editor;32 this.editor.$editor = this;33 },34 onResume: function () {35 36 },37 onUnload: function () {38 this.editor.$editor = null;39 this.editor = null;40 this.$native = null;41 },42 beginEditingIdentifier: function () {43 // unused, but for toggling between input fields.44 },45 beginEditingExpression: function () {46 // unused, but for toggling between input fields.47 },48 cycleUnitScheme: function () {49 this.editor.cycleUnitScheme();50 },51 moveCursor: function (newPosition) {52 this.editor.cursorMoved(newPosition);53 },54 updateDisplay: function (editableExpression) {55 var prefs = application.model.turo.prefs();56 var result = editableExpression.evalResult;57 var cursorPosition = editableExpression.cursorPosition;58 if (cursorPosition !== undefined) {59 this.cursorPosition = cursorPosition;60 }61 // t is a transferable object, defined in idl.62 var t = {63 id: result.id,64 cursorPosition: cursorPosition65 };66 var src = editableExpression.toString() || '',67 display = isUnderTest ? undefined : output.display;68 t.expressionToString = src;69 t.expressionLength = src.length;70 if (editableExpression.isParseable) {71 var resultToStringPrefs = {72 precisionType: "sf", 73 precisionDigits: 12, 74 useUnitRefactor: true,75 unitScheme: prefs.unitScheme,76 exponent: true, 77 prettyPrint: true78 };79 var errors = result.expressionErrors(),80 inError = errors && errors.length > 0;81 if (inError) {82 t.resultToString = 'Error';83 } else if (isUnderTest) {84 t.resultToString = result.valueToString(resultToStringPrefs);85 } else {86 t.resultToString = result.valueToHtml(resultToStringPrefs);87 }88 }89 t.expressionToString = editableExpression.toString(display);90 t.expressionIsString = false;91 t.cursorPosition = cursorPosition;92 t.autoSuffix = stringTimes(")", result.addedParens);93 t.identifierToString = result.identifierToString() || '';94 95 var identifierErrors = result.identifierErrors();96 if (identifierErrors) {97 t.identifierErrorToString = 'UMM';98 }99 t.unitScheme = prefs.unitScheme || 'Default';100 t.cursorPosition = t.cursorPosition || 0;101 // TODO this should be a method call.102 this.$native.displayStatement(t);103 },104 setEditorColor: function (colors) {105 this._colors = colors;106 },107 }108);109Object.defineProperties(EditorController.prototype, {110 lineToCursor: {111 get: function () {112 }113 },114 cursorPosition: {115 set: function (cursorPosition) {116 //this.$native.setCursorPosition(cursorPosition);117 this._cursorPosition = cursorPosition;118 },119 get: function () {120 return this._cursorPosition;121 }122 },123 statement: {124 set: function (statement) {125 this.updateDisplay(statement);126 }127 },128 isUnderTest: {129 set: function (bool) {130 isUnderTest = bool;131 if (bool) {132 testPadding = '|';133 } else {134 testPadding = undefined;135 }136 },137 },138});...
utils.js
Source:utils.js
...51export function assert(value, message) {52 if (!value) throw new Error(message)53}54export function debugAssert(value, message) {55 if (isUnderTest() && !value) throw new Error(message)56}57export function isString(obj) {58 return typeof obj === 'string' || obj instanceof String59}60export function isRegExp(obj) {61 return (62 obj instanceof RegExp ||63 Object.prototype.toString.call(obj) === '[object RegExp]'64 )65}66export function isObject(obj) {67 return typeof obj === 'object' && obj !== null68}69export function isError(obj) {70 return (71 obj instanceof Error ||72 (obj && obj.__proto__ && obj.__proto__.name === 'Error')73 )74}75const isInDebugMode = !!getFromENV('PWDEBUG')76export function isDebugMode() {77 return isInDebugMode78}79let _isUnderTest = false80export function setUnderTest() {81 _isUnderTest = true82}83export function isUnderTest() {84 return _isUnderTest85}86export function getFromENV(name) {87 let value = process.env[name]88 value =89 value === undefined90 ? process.env[`npm_config_${name.toLowerCase()}`]91 : value92 value =93 value === undefined94 ? process.env[`npm_package_config_${name.toLowerCase()}`]95 : value96 return value97}...
config.isUnderTest.stubbed.env.test.esm.js
Source:config.isUnderTest.stubbed.env.test.esm.js
1'use strict';2import test from 'tape';3import sinon from 'sinon';4import {config, DEFAULT_IS_UNDER_TEST} from '../../esm/config';5test('isUnderTest() should respond even if`IS_UNDER_TEST` environment setting is missing.', assert => {6 const sandbox = sinon.createSandbox();7 sandbox.stub(process, 'env').value({});8 assert.equal(config.isUnderTest(), DEFAULT_IS_UNDER_TEST, 'when IS_UNDER_TEST is not present in the environment isUnderTest() returns DEFAULT_IS_UNDER_TEST');9 assert.equal(DEFAULT_IS_UNDER_TEST, false, 'when IS_UNDER_TEST is not present in the environment isUnderTest() returns DEFAULT_IS_UNDER_TEST that is false');10 assert.end();11 sandbox.restore();12});13test('isUnderTest() should respond consistently with `IS_UNDER_TEST` environment setting.', assert => {14 const sandbox = sinon.createSandbox();15 sandbox.stub(process.env, 'IS_UNDER_TEST').value(true);16 assert.equal(config.isUnderTest(), true, 'when IS_UNDER_TEST equals true isUnderTest() returns true');17 sandbox.stub(process.env, 'IS_UNDER_TEST').value(false);18 assert.equal(config.isUnderTest(), false, 'when IS_UNDER_TEST equals false isUnderTest() returns false');19 sandbox.stub(process.env, 'IS_UNDER_TEST').value(1);20 assert.equal(config.isUnderTest(), true, 'when IS_UNDER_TEST is 1 isUnderTest() should returns true');21 sandbox.stub(process.env, 'IS_UNDER_TEST').value(0);22 assert.equal(config.isUnderTest(), false, 'when IS_UNDER_TEST is 0 isUnderTest() should return false');23 sandbox.stub(process.env, 'IS_UNDER_TEST').value(-1);24 assert.equal(config.isUnderTest(), true, 'when IS_UNDER_TEST is a negative number isUnderTest() should return true');25 sandbox.stub(process.env, 'IS_UNDER_TEST').value(9);26 assert.equal(config.isUnderTest(), true, 'when IS_UNDER_TEST is a number different than 0 the isUnderTest() should return true');27 sandbox.stub(process.env, 'IS_UNDER_TEST').value('TrUE');28 assert.equal(config.isUnderTest(), true, 'when IS_UNDER_TEST is a case insentitive TRUE string the isUnderTest() should return true');29 sandbox.stub(process.env, 'IS_UNDER_TEST').value('FaLsE');30 assert.equal(config.isUnderTest(), false, 'when IS_UNDER_TEST is a case insentitive FALSE the isUnderTest() string should return false');31 sandbox.stub(process.env, 'IS_UNDER_TEST').value(' FaLsE');32 assert.equal(config.isUnderTest(), false, 'when IS_UNDER_TEST is a case insentitive FALSE string the isUnderTest() should return false even when there are leading spaces in its value');33 sandbox.stub(process.env, 'IS_UNDER_TEST').value(' TRue ');34 assert.equal(config.isUnderTest(), true, 'when IS_UNDER_TEST is a case insentitive FALSE string the isUnderTest() should return true even when there are leading spaces in its value');35 sandbox.stub(process.env, 'IS_UNDER_TEST').value('YES');36 assert.throws(() => config.isUnderTest(), new TypeError(), 'when IS_UNDER_TEST has a string value that in neigher TRUE or FALSE, less that case sensivity and possibly traling or leading spaces , nor a number, then should throw an exception not to lead to ambiguous decisions');37 assert.end();38 sandbox.restore();...
config.test.esm.js
Source:config.test.esm.js
...7});8test('config has a function named isUnderTest which has no arguments and return a boolean indicating when test features are enabled for the current execution environment.', assert => {9 assert.plan(2);10 assert.equal(typeof config.isUnderTest, 'function', 'isUnderTest should be a function');11 assert.equal(typeof config.isUnderTest(), 'boolean', 'isUnderTest() should return a boolean');...
Using AI Code Generation
1const { isUnderTest } = require('playwright');2const isUnderTest = isUnderTest();3const { isUnderTest } = require('@playwright/test');4const isUnderTest = isUnderTest();5const { isUnderTest } = require('@playwright/test-runner');6const isUnderTest = isUnderTest();7const { isUnderTest } = require('@playwright/test-runner');8const isUnderTest = isUnderTest();9const { isUnderTest } = require('@playwright/test-runner');10const isUnderTest = isUnderTest();11const { isUnderTest } = require('@playwright/test-runner');12const isUnderTest = isUnderTest();
Using AI Code Generation
1const { isUnderTest } = require('@playwright/test/lib/utils/utils');2console.log(isUnderTest());3const { isUnderTest } = require('@playwright/test/lib/utils/utils');4console.log(isUnderTest());5If you want to access the isUnderTest() method in the test files, you can use the following code snippet:6const { isUnderTest } = require('@playwright/test/lib/utils/utils');7console.log(isUnderTest());
Using AI Code Generation
1const { isUnderTest } = require('@playwright/test/lib/utils/testRunner');2console.log('isUnderTest: ', isUnderTest);3const { test } = require('@playwright/test');4test('test', async ({ page }) => {5 const title = await page.title();6 expect(title).toBe('Playwright');7});
Using AI Code Generation
1const { isUnderTest } = require('playwright/lib/server/playwright.js');2console.log('isUnderTest', isUnderTest);3const { test } = require('@playwright/test');4test('isUnderTest', async ({ page }) => {5 await page.waitForTimeout(10000);6});
Using AI Code Generation
1const { isUnderTest } = require('playwright/lib/internal/telemetry/generated/telemetryReporter');2if (isUnderTest()) {3 console.log('Running tests');4} else {5 console.log('Running production');6}7const { isUnderTest } = require('playwright/lib/internal/telemetry/generated/telemetryReporter');8it('should send telemetry', async () => {9 if (isUnderTest()) {10 return;11 }12});
Using AI Code Generation
1const { test } = require('@playwright/test');2test('test', async ({ page }) => {3 if (page.context().browser()._isUnderTest()) {4 console.log('test environment');5 }6});7const { chromium } = require('playwright');8(async () => {9 const browser = await chromium.launch();10 if (browser._isUnderTest()) {11 console.log('test environment');12 }13})();
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!!