Best JavaScript code snippet using playwright-internal
runner.js
Source:runner.js
...148 testFiles.forEach(file => allTestFiles.add(file));149 }150 const webServer = config.webServer && (await _webServer.WebServer.create(config.webServer));151 let globalSetupResult;152 if (config.globalSetup) globalSetupResult = await (await this._loader.loadGlobalHook(config.globalSetup, 'globalSetup'))(this._loader.fullConfig());153 try {154 var _this$_reporter$onBeg2, _this$_reporter3, _this$_reporter$onEnd3, _this$_reporter5;155 for (const file of allTestFiles) await this._loader.loadTestFile(file);156 const preprocessRoot = new _test.Suite('');157 for (const fileSuite of this._loader.fileSuites().values()) preprocessRoot._addSuite(fileSuite);158 if (config.forbidOnly) {159 const onlyTestsAndSuites = preprocessRoot._getOnlyItems();160 if (onlyTestsAndSuites.length > 0) {161 const locations = onlyTestsAndSuites.map(testOrSuite => {162 // Skip root and file.163 const title = testOrSuite.titlePath().slice(2).join(' ');164 return `${buildItemLocation(config.rootDir, testOrSuite)} > ${title}`;165 });166 return {167 status: 'forbid-only',168 locations169 };170 }171 }172 const clashingTests = getClashingTestsPerSuite(preprocessRoot);173 if (clashingTests.size > 0) return {174 status: 'clashing-test-titles',175 clashingTests: clashingTests176 };177 filterOnly(preprocessRoot);178 filterByFocusedLine(preprocessRoot, testFileReFilters);179 const fileSuites = new Map();180 for (const fileSuite of preprocessRoot.suites) fileSuites.set(fileSuite._requireFile, fileSuite);181 const outputDirs = new Set();182 const grepMatcher = (0, _util2.createMatcher)(config.grep);183 const grepInvertMatcher = config.grepInvert ? (0, _util2.createMatcher)(config.grepInvert) : null;184 const rootSuite = new _test.Suite('');185 for (const project of projects) {186 const projectSuite = new _test.Suite(project.config.name);187 rootSuite._addSuite(projectSuite);188 for (const file of files.get(project)) {189 const fileSuite = fileSuites.get(file);190 if (!fileSuite) continue;191 for (let repeatEachIndex = 0; repeatEachIndex < project.config.repeatEach; repeatEachIndex++) {192 const cloned = project.cloneFileSuite(fileSuite, repeatEachIndex, test => {193 const grepTitle = test.titlePath().join(' ');194 if (grepInvertMatcher !== null && grepInvertMatcher !== void 0 && grepInvertMatcher(grepTitle)) return false;195 return grepMatcher(grepTitle);196 });197 if (cloned) projectSuite._addSuite(cloned);198 }199 }200 outputDirs.add(project.config.outputDir);201 }202 let total = rootSuite.allTests().length;203 if (!total) return {204 status: 'no-tests'205 };206 await Promise.all(Array.from(outputDirs).map(outputDir => removeFolderAsync(outputDir).catch(e => {})));207 let testGroups = createTestGroups(rootSuite);208 const shard = config.shard;209 if (shard) {210 const shardGroups = [];211 const shardTests = new Set(); // Each shard gets some tests.212 const shardSize = Math.floor(total / shard.total); // First few shards get one more test each.213 const extraOne = total - shardSize * shard.total;214 const currentShard = shard.current - 1; // Make it zero-based for calculations.215 const from = shardSize * currentShard + Math.min(extraOne, currentShard);216 const to = from + shardSize + (currentShard < extraOne ? 1 : 0);217 let current = 0;218 for (const group of testGroups) {219 // Any test group goes to the shard that contains the first test of this group.220 // So, this shard gets any group that starts at [from; to)221 if (current >= from && current < to) {222 shardGroups.push(group);223 for (const test of group.tests) shardTests.add(test);224 }225 current += group.tests.length;226 }227 testGroups = shardGroups;228 filterSuite(rootSuite, () => false, test => shardTests.has(test));229 total = rootSuite.allTests().length;230 }231 if (process.stdout.isTTY) {232 console.log();233 const jobs = Math.min(config.workers, testGroups.length);234 const shardDetails = shard ? `, shard ${shard.current} of ${shard.total}` : '';235 console.log(`Running ${total} test${total > 1 ? 's' : ''} using ${jobs} worker${jobs > 1 ? 's' : ''}${shardDetails}`);236 }237 let sigint = false;238 let sigintCallback;239 const sigIntPromise = new Promise(f => sigintCallback = f);240 const sigintHandler = () => {241 // We remove the handler so that second Ctrl+C immediately kills the runner242 // via the default sigint handler. This is handy in the case where our shutdown243 // takes a lot of time or is buggy.244 //245 // When running through NPM we might get multiple SIGINT signals246 // for a single Ctrl+C - this is an NPM bug present since at least NPM v6.247 // https://github.com/npm/cli/issues/1591248 // https://github.com/npm/cli/issues/2124249 //250 // Therefore, removing the handler too soon will just kill the process251 // with default handler without printing the results.252 // We work around this by giving NPM 1000ms to send us duplicate signals.253 // The side effect is that slow shutdown or bug in our runner will force254 // the user to hit Ctrl+C again after at least a second.255 setTimeout(() => process.off('SIGINT', sigintHandler), 1000);256 sigint = true;257 sigintCallback();258 };259 process.on('SIGINT', sigintHandler);260 (_this$_reporter$onBeg2 = (_this$_reporter3 = this._reporter).onBegin) === null || _this$_reporter$onBeg2 === void 0 ? void 0 : _this$_reporter$onBeg2.call(_this$_reporter3, config, rootSuite);261 this._didBegin = true;262 let hasWorkerErrors = false;263 if (!list) {264 const dispatcher = new _dispatcher.Dispatcher(this._loader, testGroups, this._reporter);265 await Promise.race([dispatcher.run(), sigIntPromise]);266 await dispatcher.stop();267 hasWorkerErrors = dispatcher.hasWorkerErrors();268 }269 if (sigint) {270 var _this$_reporter$onEnd2, _this$_reporter4;271 await ((_this$_reporter$onEnd2 = (_this$_reporter4 = this._reporter).onEnd) === null || _this$_reporter$onEnd2 === void 0 ? void 0 : _this$_reporter$onEnd2.call(_this$_reporter4, {272 status: 'interrupted'273 }));274 return {275 status: 'sigint'276 };277 }278 const failed = hasWorkerErrors || rootSuite.allTests().some(test => !test.ok());279 await ((_this$_reporter$onEnd3 = (_this$_reporter5 = this._reporter).onEnd) === null || _this$_reporter$onEnd3 === void 0 ? void 0 : _this$_reporter$onEnd3.call(_this$_reporter5, {280 status: failed ? 'failed' : 'passed'281 }));282 return {283 status: failed ? 'failed' : 'passed'284 };285 } finally {286 if (globalSetupResult && typeof globalSetupResult === 'function') await globalSetupResult(this._loader.fullConfig());287 if (config.globalTeardown) await (await this._loader.loadGlobalHook(config.globalTeardown, 'globalTeardown'))(this._loader.fullConfig());288 await (webServer === null || webServer === void 0 ? void 0 : webServer.kill());289 }290 }291}292exports.Runner = Runner;293function filterOnly(suite) {294 const suiteFilter = suite => suite._only;295 const testFilter = test => test._only;296 return filterSuite(suite, suiteFilter, testFilter);297}298function filterByFocusedLine(suite, focusedTestFileLines) {299 const testFileLineMatches = (testFileName, testLine) => focusedTestFileLines.some(({300 re,301 line...
loader.js
Source:loader.js
...108 } finally {109 (0, _globals.setCurrentlyLoadingFileSuite)(undefined);110 }111 }112 async loadGlobalHook(file, name) {113 let hook = await this._requireOrImport(file);114 if (hook && typeof hook === 'object' && 'default' in hook) hook = hook['default'];115 if (typeof hook !== 'function') throw (0, _util.errorWithFile)(file, `${name} file must export a single function.`);116 return hook;117 }118 async loadReporter(file) {119 let func = await this._requireOrImport(path.resolve(this._fullConfig.rootDir, file));120 if (func && typeof func === 'object' && 'default' in func) func = func['default'];121 if (typeof func !== 'function') throw (0, _util.errorWithFile)(file, `reporter file must export a single class.`);122 return func;123 }124 fullConfig() {125 return this._fullConfig;126 }...
Using AI Code Generation
1const playwright = require('playwright');2(async () => {3 const browser = await playwright.chromium.launch();4 const context = await browser.newContext();5 const page = await context.newPage();6 await page.screenshot({ path: 'example.png' });7 await browser.close();8})();9const { loadGlobalHook } = require('playwright-core/lib/server/globalHook');10await loadGlobalHook(require.resolve('playwright-core/lib/server/globalHook'));11[Apache 2.0](LICENSE)
Using AI Code Generation
1const { loadGlobalHook } = require('playwright/lib/server/trace/recorder/recorderApp');2loadGlobalHook(require('playwright'));3const playwright = require('playwright');4const { expect } = require('chai');5const { test } = require('@playwright/test');6test.describe('Test Suite', function () {7 test.beforeAll(async ({ browser }) => {8 page = await browser.newPage();9 });10 test('Test Case', async ({ page }) => {11 await page.click('text=Get Started');12 await page.click('text=Docs');13 await page.click('text=API');14 await page.click('text=Sele
Using AI Code Generation
1const { chromium } = require('playwright');2(async () => {3 const browser = await chromium.launch();4 const page = await browser.newPage();5 await page.screenshot({ path: `example.png` });6 await browser.close();7})();
Using AI Code Generation
1const { loadGlobalHook } = require('playwright-core/lib/server/browserServer');2loadGlobalHook('chromium');3const { loadGlobalHook } = require('playwright-core/lib/server/browserServer');4loadGlobalHook('firefox');5const { loadGlobalHook } = require('playwright-core/lib/server/browserServer');6loadGlobalHook('webkit');7const { loadGlobalHook } = require('playwright-core/lib/server/browserServer');8loadGlobalHook('all');9const { loadGlobalHook } = require('playwright-core/lib/server/browserServer');10loadGlobalHook('none');11const { chromium } = require('playwright-core');12const { loadGlobalHook } = require('playwright-core/lib/server/browserServer');13(async () => {14 loadGlobalHook('chromium');15 const browser = await chromium.launch();16 const page = await browser.newPage();17 await page.screenshot({ path: 'example.png' });18 await browser.close();19})();20module.exports = {21 globalSetup: require.resolve('./globalSetup'),22 globalTeardown: require.resolve('./globalTeardown'),23 setupFilesAfterEnv: [require.resolve('./setupFilesAfterEnv')],24};25const { loadGlobalHook } = require('playwright-core/lib/server/browserServer');26module.exports = async function globalSetup() {27 loadGlobalHook('chromium');28};29const { loadGlobalHook } = require('playwright-core/lib/server/browserServer');30module.exports = async function setupFilesAfterEnv() {31 loadGlobalHook('chromium');32};
Using AI Code Generation
1const { loadGlobalHook } = require('playwright/lib/server/trace/recorder/recorderApp');2loadGlobalHook();3const { loadGlobalHook } = require('playwright/lib/server/trace/recorder/recorderApp');4loadGlobalHook();5const { loadGlobalHook } = require('playwright/lib/server/trace/recorder/recorderApp');6loadGlobalHook();7const { loadGlobalHook } = require('playwright/lib/server/trace/recorder/recorderApp');8loadGlobalHook();9const { loadGlobalHook } = require('playwright/lib/server/trace/recorder/recorderApp');10loadGlobalHook();11const { loadGlobalHook } = require('playwright/lib/server/trace/recorder/recorderApp');12loadGlobalHook();13const { loadGlobalHook } = require('playwright/lib/server/trace/recorder/recorderApp');14loadGlobalHook();
Using AI Code Generation
1const { loadGlobalHook } = require('playwright/lib/utils/hooks');2loadGlobalHook('test', async (testInfo, runTest) => {3 console.log('before test');4 await runTest(testInfo);5 console.log('after test');6});7const { loadFixture } = require('playwright/lib/utils/fixtures');8const { test } = require('@playwright/test');9test('fixture test', async ({ page }) => {10 const { log } = await loadFixture(page, 'log', { name: 'fixture' });11 expect(log).toBe('fixture');12});13const { loadWorkerFixture } = require('playwright/lib/utils/fixtures');14const { test } = require('@playwright/test');15test('worker fixture test', async ({ page }) => {16 const { log } = await loadWorkerFixture(page, 'log', { name: 'fixture' });17 expect(log).toBe('fixture');18});19const { registerFixture } = require('playwright/lib/utils/fixtures');20const { test } = require('@playwright/test');21registerFixture('log', async ({}, use) => {22 const log = [];23 await use({24 log: (message) => {25 log.push(message);26 },27 });28 return { log };29});30test('fixture test', async ({ log }) => {31 log('test');32 expect(log).toEqual(['test']);33});34const { registerWorkerFixture } = require('playwright/lib/utils/fixtures');35const { test } = require('@playwright/test');36registerWorkerFixture('log', async ({}, use) => {37 const log = [];38 await use({39 log: (message) => {40 log.push(message);41 },42 });43 return { log };44});45test('worker fixture test', async ({ log }) => {46 log('test');47 expect(log).toEqual(['test
Using AI Code Generation
1const { loadGlobalHook } = require('playwright/lib/utils/registry');2loadGlobalHook('test', async (context, options) => {3 console.log('test hook loaded');4 return {};5});6module.exports = {7 test: {8 launchOptions: {9 },10 contextOptions: {11 },12 browserOptions: {13 },14 },15};16module.exports = {17};18describe('Playwright', () => {19 it('should be able to launch browser', async () => {20 const browser = await context.browser();21 expect(browser).toBeDefined();22 });23});24### [jest-playwright-preset](
Using AI Code Generation
1const { loadGlobalHook } = require('playwright/lib/server/trace/recorder/recorderApp');2loadGlobalHook();3const { test, expect } = require('@playwright/test');4test('basic test', async ({ page }) => {5 expect(await page.textContent('.navbar__inner')).toContain('Playwright');6});7const { test, expect } = require('@playwright/test');8test.use({ trace: 'trace.zip' });9test('basic test', async ({ page }) => {10 expect(await page.textContent('.navbar__inner')).toContain('Playwright');11});12const { test, expect } = require('@playwright/test');13test.use({ trace: 'trace.zip' });14test('basic test', async ({ page }) => {15 expect(await page.textContent('.navbar__inner')).toContain('Playwright');16});
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!!