Best JavaScript code snippet using playwright-internal
loader.js
Source:loader.js
1"use strict";2Object.defineProperty(exports, "__esModule", {3 value: true4});5exports.Loader = void 0;6var _transform = require("./transform");7var _util = require("./util");8var _globals = require("./globals");9var _test = require("./test");10var path = _interopRequireWildcard(require("path"));11var url = _interopRequireWildcard(require("url"));12var fs = _interopRequireWildcard(require("fs"));13var _project = require("./project");14var _runner = require("./runner");15function _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); }16function _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; }17/**18 * Copyright Microsoft Corporation. All rights reserved.19 *20 * Licensed under the Apache License, Version 2.0 (the "License");21 * you may not use this file except in compliance with the License.22 * You may obtain a copy of the License at23 *24 * http://www.apache.org/licenses/LICENSE-2.025 *26 * Unless required by applicable law or agreed to in writing, software27 * distributed under the License is distributed on an "AS IS" BASIS,28 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.29 * See the License for the specific language governing permissions and30 * limitations under the License.31 */32class Loader {33 constructor(defaultConfig, configOverrides) {34 this._defaultConfig = void 0;35 this._configOverrides = void 0;36 this._fullConfig = void 0;37 this._config = {};38 this._configFile = void 0;39 this._projects = [];40 this._fileSuites = new Map();41 this._defaultConfig = defaultConfig;42 this._configOverrides = configOverrides;43 this._fullConfig = baseFullConfig;44 }45 static async deserialize(data) {46 const loader = new Loader(data.defaultConfig, data.overrides);47 if ('file' in data.configFile) await loader.loadConfigFile(data.configFile.file);else loader.loadEmptyConfig(data.configFile.rootDir);48 return loader;49 }50 async loadConfigFile(file) {51 if (this._configFile) throw new Error('Cannot load two config files');52 let config = await this._requireOrImport(file);53 if (config && typeof config === 'object' && 'default' in config) config = config['default'];54 this._config = config;55 this._configFile = file;56 const rawConfig = { ...config57 };58 this._processConfigObject(path.dirname(file));59 return rawConfig;60 }61 loadEmptyConfig(rootDir) {62 this._config = {};63 this._processConfigObject(rootDir);64 }65 _processConfigObject(rootDir) {66 validateConfig(this._configFile || '<default config>', this._config); // Resolve script hooks relative to the root dir.67 if (this._config.globalSetup) this._config.globalSetup = resolveScript(this._config.globalSetup, rootDir);68 if (this._config.globalTeardown) this._config.globalTeardown = resolveScript(this._config.globalTeardown, rootDir);69 const configUse = (0, _util.mergeObjects)(this._defaultConfig.use, this._config.use);70 this._config = (0, _util.mergeObjects)((0, _util.mergeObjects)(this._defaultConfig, this._config), {71 use: configUse72 });73 if (this._config.testDir !== undefined) this._config.testDir = path.resolve(rootDir, this._config.testDir);74 const projects = 'projects' in this._config && this._config.projects !== undefined ? this._config.projects : [this._config];75 this._fullConfig.rootDir = this._config.testDir || rootDir;76 this._fullConfig.forbidOnly = takeFirst(this._configOverrides.forbidOnly, this._config.forbidOnly, baseFullConfig.forbidOnly);77 this._fullConfig.globalSetup = takeFirst(this._configOverrides.globalSetup, this._config.globalSetup, baseFullConfig.globalSetup);78 this._fullConfig.globalTeardown = takeFirst(this._configOverrides.globalTeardown, this._config.globalTeardown, baseFullConfig.globalTeardown);79 this._fullConfig.globalTimeout = takeFirst(this._configOverrides.globalTimeout, this._configOverrides.globalTimeout, this._config.globalTimeout, baseFullConfig.globalTimeout);80 this._fullConfig.grep = takeFirst(this._configOverrides.grep, this._config.grep, baseFullConfig.grep);81 this._fullConfig.grepInvert = takeFirst(this._configOverrides.grepInvert, this._config.grepInvert, baseFullConfig.grepInvert);82 this._fullConfig.maxFailures = takeFirst(this._configOverrides.maxFailures, this._config.maxFailures, baseFullConfig.maxFailures);83 this._fullConfig.preserveOutput = takeFirst(this._configOverrides.preserveOutput, this._config.preserveOutput, baseFullConfig.preserveOutput);84 this._fullConfig.reporter = takeFirst(toReporters(this._configOverrides.reporter), resolveReporters(this._config.reporter, rootDir), baseFullConfig.reporter);85 this._fullConfig.reportSlowTests = takeFirst(this._configOverrides.reportSlowTests, this._config.reportSlowTests, baseFullConfig.reportSlowTests);86 this._fullConfig.quiet = takeFirst(this._configOverrides.quiet, this._config.quiet, baseFullConfig.quiet);87 this._fullConfig.shard = takeFirst(this._configOverrides.shard, this._config.shard, baseFullConfig.shard);88 this._fullConfig.updateSnapshots = takeFirst(this._configOverrides.updateSnapshots, this._config.updateSnapshots, baseFullConfig.updateSnapshots);89 this._fullConfig.workers = takeFirst(this._configOverrides.workers, this._config.workers, baseFullConfig.workers);90 this._fullConfig.webServer = takeFirst(this._configOverrides.webServer, this._config.webServer, baseFullConfig.webServer);91 for (const project of projects) this._addProject(project, this._fullConfig.rootDir);92 this._fullConfig.projects = this._projects.map(p => p.config);93 }94 async loadTestFile(file) {95 if (this._fileSuites.has(file)) return this._fileSuites.get(file);96 try {97 const suite = new _test.Suite(path.relative(this._fullConfig.rootDir, file) || path.basename(file));98 suite._requireFile = file;99 suite.location = {100 file,101 line: 0,102 column: 0103 };104 (0, _globals.setCurrentlyLoadingFileSuite)(suite);105 await this._requireOrImport(file);106 this._fileSuites.set(file, suite);107 return suite;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 }127 projects() {128 return this._projects;129 }130 fileSuites() {131 return this._fileSuites;132 }133 serialize() {134 return {135 defaultConfig: this._defaultConfig,136 configFile: this._configFile ? {137 file: this._configFile138 } : {139 rootDir: this._fullConfig.rootDir140 },141 overrides: this._configOverrides142 };143 }144 _addProject(projectConfig, rootDir) {145 let testDir = takeFirst(projectConfig.testDir, rootDir);146 if (!path.isAbsolute(testDir)) testDir = path.resolve(rootDir, testDir);147 let outputDir = takeFirst(this._configOverrides.outputDir, projectConfig.outputDir, this._config.outputDir, path.resolve(process.cwd(), 'test-results'));148 if (!path.isAbsolute(outputDir)) outputDir = path.resolve(rootDir, outputDir);149 const fullProject = {150 define: takeFirst(this._configOverrides.define, projectConfig.define, this._config.define, []),151 expect: takeFirst(this._configOverrides.expect, projectConfig.expect, this._config.expect, undefined),152 outputDir,153 repeatEach: takeFirst(this._configOverrides.repeatEach, projectConfig.repeatEach, this._config.repeatEach, 1),154 retries: takeFirst(this._configOverrides.retries, projectConfig.retries, this._config.retries, 0),155 metadata: takeFirst(this._configOverrides.metadata, projectConfig.metadata, this._config.metadata, undefined),156 name: takeFirst(this._configOverrides.name, projectConfig.name, this._config.name, ''),157 testDir,158 testIgnore: takeFirst(this._configOverrides.testIgnore, projectConfig.testIgnore, this._config.testIgnore, []),159 testMatch: takeFirst(this._configOverrides.testMatch, projectConfig.testMatch, this._config.testMatch, '**/?(*.)@(spec|test).@(ts|js|mjs)'),160 timeout: takeFirst(this._configOverrides.timeout, projectConfig.timeout, this._config.timeout, 10000),161 use: (0, _util.mergeObjects)((0, _util.mergeObjects)(this._config.use, projectConfig.use), this._configOverrides.use)162 };163 this._projects.push(new _project.ProjectImpl(fullProject, this._projects.length));164 }165 async _requireOrImport(file) {166 const revertBabelRequire = (0, _transform.installTransform)();167 try {168 const esmImport = () => eval(`import(${JSON.stringify(url.pathToFileURL(file))})`);169 if (file.endsWith('.mjs')) {170 return await esmImport();171 } else {172 try {173 return require(file);174 } catch (e) {175 // Attempt to load this module as ESM if a normal require didn't work.176 if (e.code === 'ERR_REQUIRE_ESM') return await esmImport();177 throw e;178 }179 }180 } catch (error) {181 if (error instanceof SyntaxError && error.message.includes('Cannot use import statement outside a module')) throw (0, _util.errorWithFile)(file, 'JavaScript files must end with .mjs to use import.');182 throw error;183 } finally {184 revertBabelRequire();185 }186 }187}188exports.Loader = Loader;189function takeFirst(...args) {190 for (const arg of args) {191 if (arg !== undefined) return arg;192 }193 return undefined;194}195function toReporters(reporters) {196 if (!reporters) return;197 if (typeof reporters === 'string') return [[reporters]];198 return reporters;199}200function validateConfig(file, config) {201 if (typeof config !== 'object' || !config) throw (0, _util.errorWithFile)(file, `Configuration file must export a single object`);202 validateProject(file, config, 'config');203 if ('forbidOnly' in config && config.forbidOnly !== undefined) {204 if (typeof config.forbidOnly !== 'boolean') throw (0, _util.errorWithFile)(file, `config.forbidOnly must be a boolean`);205 }206 if ('globalSetup' in config && config.globalSetup !== undefined) {207 if (typeof config.globalSetup !== 'string') throw (0, _util.errorWithFile)(file, `config.globalSetup must be a string`);208 }209 if ('globalTeardown' in config && config.globalTeardown !== undefined) {210 if (typeof config.globalTeardown !== 'string') throw (0, _util.errorWithFile)(file, `config.globalTeardown must be a string`);211 }212 if ('globalTimeout' in config && config.globalTimeout !== undefined) {213 if (typeof config.globalTimeout !== 'number' || config.globalTimeout < 0) throw (0, _util.errorWithFile)(file, `config.globalTimeout must be a non-negative number`);214 }215 if ('grep' in config && config.grep !== undefined) {216 if (Array.isArray(config.grep)) {217 config.grep.forEach((item, index) => {218 if (!(0, _util.isRegExp)(item)) throw (0, _util.errorWithFile)(file, `config.grep[${index}] must be a RegExp`);219 });220 } else if (!(0, _util.isRegExp)(config.grep)) {221 throw (0, _util.errorWithFile)(file, `config.grep must be a RegExp`);222 }223 }224 if ('grepInvert' in config && config.grepInvert !== undefined) {225 if (Array.isArray(config.grepInvert)) {226 config.grepInvert.forEach((item, index) => {227 if (!(0, _util.isRegExp)(item)) throw (0, _util.errorWithFile)(file, `config.grepInvert[${index}] must be a RegExp`);228 });229 } else if (!(0, _util.isRegExp)(config.grepInvert)) {230 throw (0, _util.errorWithFile)(file, `config.grep must be a RegExp`);231 }232 }233 if ('maxFailures' in config && config.maxFailures !== undefined) {234 if (typeof config.maxFailures !== 'number' || config.maxFailures < 0) throw (0, _util.errorWithFile)(file, `config.maxFailures must be a non-negative number`);235 }236 if ('preserveOutput' in config && config.preserveOutput !== undefined) {237 if (typeof config.preserveOutput !== 'string' || !['always', 'never', 'failures-only'].includes(config.preserveOutput)) throw (0, _util.errorWithFile)(file, `config.preserveOutput must be one of "always", "never" or "failures-only"`);238 }239 if ('projects' in config && config.projects !== undefined) {240 if (!Array.isArray(config.projects)) throw (0, _util.errorWithFile)(file, `config.projects must be an array`);241 config.projects.forEach((project, index) => {242 validateProject(file, project, `config.projects[${index}]`);243 });244 }245 if ('quiet' in config && config.quiet !== undefined) {246 if (typeof config.quiet !== 'boolean') throw (0, _util.errorWithFile)(file, `config.quiet must be a boolean`);247 }248 if ('reporter' in config && config.reporter !== undefined) {249 if (Array.isArray(config.reporter)) {250 config.reporter.forEach((item, index) => {251 if (!Array.isArray(item) || item.length <= 0 || item.length > 2 || typeof item[0] !== 'string') throw (0, _util.errorWithFile)(file, `config.reporter[${index}] must be a tuple [name, optionalArgument]`);252 });253 } else if (typeof config.reporter !== 'string') {254 throw (0, _util.errorWithFile)(file, `config.reporter must be a string`);255 }256 }257 if ('reportSlowTests' in config && config.reportSlowTests !== undefined && config.reportSlowTests !== null) {258 if (!config.reportSlowTests || typeof config.reportSlowTests !== 'object') throw (0, _util.errorWithFile)(file, `config.reportSlowTests must be an object`);259 if (!('max' in config.reportSlowTests) || typeof config.reportSlowTests.max !== 'number' || config.reportSlowTests.max < 0) throw (0, _util.errorWithFile)(file, `config.reportSlowTests.max must be a non-negative number`);260 if (!('threshold' in config.reportSlowTests) || typeof config.reportSlowTests.threshold !== 'number' || config.reportSlowTests.threshold < 0) throw (0, _util.errorWithFile)(file, `config.reportSlowTests.threshold must be a non-negative number`);261 }262 if ('shard' in config && config.shard !== undefined && config.shard !== null) {263 if (!config.shard || typeof config.shard !== 'object') throw (0, _util.errorWithFile)(file, `config.shard must be an object`);264 if (!('total' in config.shard) || typeof config.shard.total !== 'number' || config.shard.total < 1) throw (0, _util.errorWithFile)(file, `config.shard.total must be a positive number`);265 if (!('current' in config.shard) || typeof config.shard.current !== 'number' || config.shard.current < 1 || config.shard.current > config.shard.total) throw (0, _util.errorWithFile)(file, `config.shard.current must be a positive number, not greater than config.shard.total`);266 }267 if ('updateSnapshots' in config && config.updateSnapshots !== undefined) {268 if (typeof config.updateSnapshots !== 'string' || !['all', 'none', 'missing'].includes(config.updateSnapshots)) throw (0, _util.errorWithFile)(file, `config.updateSnapshots must be one of "all", "none" or "missing"`);269 }270 if ('workers' in config && config.workers !== undefined) {271 if (typeof config.workers !== 'number' || config.workers <= 0) throw (0, _util.errorWithFile)(file, `config.workers must be a positive number`);272 }273}274function validateProject(file, project, title) {275 if (typeof project !== 'object' || !project) throw (0, _util.errorWithFile)(file, `${title} must be an object`);276 if ('define' in project && project.define !== undefined) {277 if (Array.isArray(project.define)) {278 project.define.forEach((item, index) => {279 validateDefine(file, item, `${title}.define[${index}]`);280 });281 } else {282 validateDefine(file, project.define, `${title}.define`);283 }284 }285 if ('name' in project && project.name !== undefined) {286 if (typeof project.name !== 'string') throw (0, _util.errorWithFile)(file, `${title}.name must be a string`);287 }288 if ('outputDir' in project && project.outputDir !== undefined) {289 if (typeof project.outputDir !== 'string') throw (0, _util.errorWithFile)(file, `${title}.outputDir must be a string`);290 }291 if ('repeatEach' in project && project.repeatEach !== undefined) {292 if (typeof project.repeatEach !== 'number' || project.repeatEach < 0) throw (0, _util.errorWithFile)(file, `${title}.repeatEach must be a non-negative number`);293 }294 if ('retries' in project && project.retries !== undefined) {295 if (typeof project.retries !== 'number' || project.retries < 0) throw (0, _util.errorWithFile)(file, `${title}.retries must be a non-negative number`);296 }297 if ('testDir' in project && project.testDir !== undefined) {298 if (typeof project.testDir !== 'string') throw (0, _util.errorWithFile)(file, `${title}.testDir must be a string`);299 }300 for (const prop of ['testIgnore', 'testMatch']) {301 if (prop in project && project[prop] !== undefined) {302 const value = project[prop];303 if (Array.isArray(value)) {304 value.forEach((item, index) => {305 if (typeof item !== 'string' && !(0, _util.isRegExp)(item)) throw (0, _util.errorWithFile)(file, `${title}.${prop}[${index}] must be a string or a RegExp`);306 });307 } else if (typeof value !== 'string' && !(0, _util.isRegExp)(value)) {308 throw (0, _util.errorWithFile)(file, `${title}.${prop} must be a string or a RegExp`);309 }310 }311 }312 if ('timeout' in project && project.timeout !== undefined) {313 if (typeof project.timeout !== 'number' || project.timeout < 0) throw (0, _util.errorWithFile)(file, `${title}.timeout must be a non-negative number`);314 }315 if ('use' in project && project.use !== undefined) {316 if (!project.use || typeof project.use !== 'object') throw (0, _util.errorWithFile)(file, `${title}.use must be an object`);317 }318}319function validateDefine(file, define, title) {320 if (!define || typeof define !== 'object' || !define.test || !define.fixtures) throw (0, _util.errorWithFile)(file, `${title} must be an object with "test" and "fixtures" properties`);321}322const baseFullConfig = {323 forbidOnly: false,324 globalSetup: null,325 globalTeardown: null,326 globalTimeout: 0,327 grep: /.*/,328 grepInvert: null,329 maxFailures: 0,330 preserveOutput: 'always',331 projects: [],332 reporter: [['list']],333 reportSlowTests: null,334 rootDir: path.resolve(process.cwd()),335 quiet: false,336 shard: null,337 updateSnapshots: 'missing',338 workers: 1,339 webServer: null340};341function resolveReporters(reporters, rootDir) {342 var _toReporters;343 return (_toReporters = toReporters(reporters)) === null || _toReporters === void 0 ? void 0 : _toReporters.map(([id, arg]) => {344 if (_runner.builtInReporters.includes(id)) return [id, arg];345 return [require.resolve(id, {346 paths: [rootDir]347 }), arg];348 });349}350function resolveScript(id, rootDir) {351 const localPath = path.resolve(rootDir, id);352 if (fs.existsSync(localPath)) return localPath;353 return require.resolve(id, {354 paths: [rootDir]355 });...
testType.js
Source:testType.js
1"use strict";2Object.defineProperty(exports, "__esModule", {3 value: true4});5exports.rootTestType = exports.TestTypeImpl = exports.DeclaredFixtures = void 0;6var _expect = require("./expect");7var _globals = require("./globals");8var _test = require("./test");9var _transform = require("./transform");10var _util = require("./util");11/**12 * Copyright (c) Microsoft Corporation.13 *14 * Licensed under the Apache License, Version 2.0 (the "License");15 * you may not use this file except in compliance with the License.16 * You may obtain a copy of the License at17 *18 * http://www.apache.org/licenses/LICENSE-2.019 *20 * Unless required by applicable law or agreed to in writing, software21 * distributed under the License is distributed on an "AS IS" BASIS,22 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.23 * See the License for the specific language governing permissions and24 * limitations under the License.25 */26const countByFile = new Map();27class DeclaredFixtures {28 constructor() {29 this.testType = void 0;30 this.location = void 0;31 }32}33exports.DeclaredFixtures = DeclaredFixtures;34class TestTypeImpl {35 constructor(fixtures) {36 this.fixtures = void 0;37 this.test = void 0;38 this.fixtures = fixtures;39 const test = (0, _transform.wrapFunctionWithLocation)(this._createTest.bind(this, 'default'));40 test.expect = _expect.expect;41 test.only = (0, _transform.wrapFunctionWithLocation)(this._createTest.bind(this, 'only'));42 test.describe = (0, _transform.wrapFunctionWithLocation)(this._describe.bind(this, 'default'));43 test.describe.only = (0, _transform.wrapFunctionWithLocation)(this._describe.bind(this, 'only'));44 test.describe.serial = (0, _transform.wrapFunctionWithLocation)(this._describe.bind(this, 'serial'));45 test.describe.serial.only = (0, _transform.wrapFunctionWithLocation)(this._describe.bind(this, 'serial.only'));46 test.beforeEach = (0, _transform.wrapFunctionWithLocation)(this._hook.bind(this, 'beforeEach'));47 test.afterEach = (0, _transform.wrapFunctionWithLocation)(this._hook.bind(this, 'afterEach'));48 test.beforeAll = (0, _transform.wrapFunctionWithLocation)(this._hook.bind(this, 'beforeAll'));49 test.afterAll = (0, _transform.wrapFunctionWithLocation)(this._hook.bind(this, 'afterAll'));50 test.skip = (0, _transform.wrapFunctionWithLocation)(this._modifier.bind(this, 'skip'));51 test.fixme = (0, _transform.wrapFunctionWithLocation)(this._modifier.bind(this, 'fixme'));52 test.fail = (0, _transform.wrapFunctionWithLocation)(this._modifier.bind(this, 'fail'));53 test.slow = (0, _transform.wrapFunctionWithLocation)(this._modifier.bind(this, 'slow'));54 test.setTimeout = (0, _transform.wrapFunctionWithLocation)(this._setTimeout.bind(this));55 test.step = (0, _transform.wrapFunctionWithLocation)(this._step.bind(this));56 test.use = (0, _transform.wrapFunctionWithLocation)(this._use.bind(this));57 test.extend = (0, _transform.wrapFunctionWithLocation)(this._extend.bind(this));58 test.declare = (0, _transform.wrapFunctionWithLocation)(this._declare.bind(this));59 this.test = test;60 }61 _createTest(type, location, title, fn) {62 throwIfRunningInsideJest();63 const suite = (0, _globals.currentlyLoadingFileSuite)();64 if (!suite) throw (0, _util.errorWithLocation)(location, `test() can only be called in a test file`);65 const ordinalInFile = countByFile.get(suite._requireFile) || 0;66 countByFile.set(suite._requireFile, ordinalInFile + 1);67 const test = new _test.TestCase('test', title, fn, ordinalInFile, this, location);68 test._requireFile = suite._requireFile;69 suite._addTest(test);70 if (type === 'only') test._only = true;71 if (type === 'skip') test.expectedStatus = 'skipped';72 }73 _describe(type, location, title, fn) {74 throwIfRunningInsideJest();75 const suite = (0, _globals.currentlyLoadingFileSuite)();76 if (!suite) throw (0, _util.errorWithLocation)(location, `describe() can only be called in a test file`);77 if (typeof title === 'function') {78 throw (0, _util.errorWithLocation)(location, ['It looks like you are calling describe() without the title. Pass the title as a first argument:', `test.describe('my test group', () => {`, ` // Declare tests here`, `});`].join('\n'));79 }80 const child = new _test.Suite(title);81 child._requireFile = suite._requireFile;82 child._isDescribe = true;83 child.location = location;84 suite._addSuite(child);85 if (type === 'only' || type === 'serial.only') child._only = true;86 if (type === 'serial' || type === 'serial.only') child._serial = true;87 (0, _globals.setCurrentlyLoadingFileSuite)(child);88 fn();89 (0, _globals.setCurrentlyLoadingFileSuite)(suite);90 }91 _hook(name, location, fn) {92 const suite = (0, _globals.currentlyLoadingFileSuite)();93 if (!suite) throw (0, _util.errorWithLocation)(location, `${name} hook can only be called in a test file`);94 if (name === 'beforeAll' || name === 'afterAll') {95 const hook = new _test.TestCase(name, name, fn, 0, this, location);96 hook._requireFile = suite._requireFile;97 suite._addAllHook(hook);98 } else {99 suite._eachHooks.push({100 type: name,101 fn,102 location103 });104 }105 }106 _modifier(type, location, ...modifierArgs) {107 const suite = (0, _globals.currentlyLoadingFileSuite)();108 if (suite) {109 if (typeof modifierArgs[0] === 'string' && typeof modifierArgs[1] === 'function') {110 // Support for test.skip('title', () => {})111 this._createTest('skip', location, modifierArgs[0], modifierArgs[1]);112 return;113 }114 if (typeof modifierArgs[0] === 'function') {115 suite._modifiers.push({116 type,117 fn: modifierArgs[0],118 location,119 description: modifierArgs[1]120 });121 } else {122 if (modifierArgs.length >= 1 && !modifierArgs[0]) return;123 const description = modifierArgs[1];124 suite._annotations.push({125 type,126 description127 });128 }129 return;130 }131 const testInfo = (0, _globals.currentTestInfo)();132 if (!testInfo) throw (0, _util.errorWithLocation)(location, `test.${type}() can only be called inside test, describe block or fixture`);133 if (typeof modifierArgs[0] === 'function') throw (0, _util.errorWithLocation)(location, `test.${type}() with a function can only be called inside describe block`);134 testInfo[type](...modifierArgs);135 }136 _setTimeout(location, timeout) {137 const suite = (0, _globals.currentlyLoadingFileSuite)();138 if (suite) {139 suite._timeout = timeout;140 return;141 }142 const testInfo = (0, _globals.currentTestInfo)();143 if (!testInfo) throw (0, _util.errorWithLocation)(location, `test.setTimeout() can only be called from a test`);144 testInfo.setTimeout(timeout);145 }146 _use(location, fixtures) {147 const suite = (0, _globals.currentlyLoadingFileSuite)();148 if (!suite) throw (0, _util.errorWithLocation)(location, `test.use() can only be called in a test file`);149 suite._use.push({150 fixtures,151 location152 });153 }154 async _step(location, title, body) {155 const testInfo = (0, _globals.currentTestInfo)();156 if (!testInfo) throw (0, _util.errorWithLocation)(location, `test.step() can only be called from a test`);157 const complete = testInfo._addStep('test.step', title);158 try {159 await body();160 complete();161 } catch (e) {162 complete((0, _util.serializeError)(e));163 throw e;164 }165 }166 _extend(location, fixtures) {167 const fixturesWithLocation = {168 fixtures,169 location170 };171 return new TestTypeImpl([...this.fixtures, fixturesWithLocation]).test;172 }173 _declare(location) {174 const declared = new DeclaredFixtures();175 declared.location = location;176 const child = new TestTypeImpl([...this.fixtures, declared]);177 declared.testType = child;178 return child.test;179 }180}181exports.TestTypeImpl = TestTypeImpl;182function throwIfRunningInsideJest() {183 if (process.env.JEST_WORKER_ID) {184 throw new Error(`Playwright Test needs to be invoked via 'npx playwright test' and excluded from Jest test runs.\n` + `Creating one directory for Playwright tests and one for Jest is the recommended way of doing it.\n` + `See https://playwright.dev/docs/intro/ for more information about Playwright Test.`);185 }186}187const rootTestType = new TestTypeImpl([]);...
globals.js
Source:globals.js
...28function currentTestInfo() {29 return currentTestInfoValue;30}31let currentFileSuite;32function setCurrentlyLoadingFileSuite(suite) {33 currentFileSuite = suite;34}35function currentlyLoadingFileSuite() {36 return currentFileSuite;...
Using AI Code Generation
1const { setCurrentlyLoadingFileSuite } = require('@playwright/test');2setCurrentlyLoadingFileSuite('test.js');3const { setCurrentlyLoadingFileTest } = require('@playwright/test');4setCurrentlyLoadingFileTest('test.js');5const { setCurrentlyLoadingFileFixture } = require('@playwright/test');6setCurrentlyLoadingFileFixture('test.js');7const { setCurrentlyLoadingFileWorker } = require('@playwright/test');8setCurrentlyLoadingFileWorker('test.js');9[Apache 2.0](LICENSE)
Using AI Code Generation
1const { setCurrentlyLoadingFileSuite } = require('@playwright/test');2setCurrentlyLoadingFileSuite(__filename);3const { test } = require('@playwright/test');4test.describe('My suite', () => {5 test('My test', async ({ page }) => {6 });7});8const { test } = require('@playwright/test');9test.describe('My suite', () => {10 test('My test', async ({ page }) => {11 });12});13const { setCurrentlyLoadingFileSuite } = require('@playwright/test');14setCurrentlyLoadingFileSuite(__filename);15const { test } = require('@playwright/test');16test.describe('My suite', () => {17 test.describe('My nested suite', () => {18 test('My test', async ({ page }) => {19 });20 });21});22const { test } = require('@playwright/test');23test.describe('My suite', () => {24 test.describe('My nested suite', () => {25 test('My test', async ({ page }) => {26 });27 });28});29const { setCurrentlyLoadingFileSuite } = require('@playwright/test');30setCurrentlyLoadingFileSuite(__filename);31const { test } = require('@playwright/test');32test.describe('My suite', () => {33 test.describe('My nested suite', () => {34 test('My test', async ({ page }) => {
Using AI Code Generation
1const fs = require("fs");2const path = require("path");3const { test, expect } = require("@playwright/test");4const { setCurrentlyLoadingFileSuite } = require("@playwright/test/lib/test");5function beforeTestFile(testFileName) {6 const testSuiteName = path.basename(testFileName, path.extname(testFileName));7 setCurrentlyLoadingFileSuite(testSuiteName);8}9function afterTestFile() {10 setCurrentlyLoadingFileSuite("");11}12const runner = test.createRunner();13const testFileLoader = test.createTestFileLoader();14const testFiles = testFileLoader.loadFiles();15for (const testFile of testFiles) {16 beforeTestFile(testFile);17 require(testFile);18 afterTestFile();19}20const { test, expect } = require("@playwright/test");21test("Test 1", async ({ page }) => {22 await page.click('"Get Started"');23 await page.click('"Docs"');
Using AI Code Generation
1const { setCurrentlyLoadingFileSuite } = require('@playwright/test');2describe('my test suite', () => {3 beforeAll(async () => {4 setCurrentlyLoadingFileSuite('my test suite');5 });6});7### `setCurrentlyLoadingFileSuite(name)`8[Apache 2.0](LICENSE)
Using AI Code Generation
1const { setCurrentlyLoadingFileSuite } = require('playwright/lib/test/workerRunner');2setCurrentlyLoadingFileSuite({3 annotations: {},4});5const { setCurrentlyLoadingFileTest } = require('playwright/lib/test/workerRunner');6setCurrentlyLoadingFileTest({7 annotations: {},8});9const { setCurrentlyLoadingFileFixture } = require('playwright/lib/test/workerRunner');10setCurrentlyLoadingFileFixture({11 annotations: {},12});13### `setCurrentlyLoadingFileSuite(suite)`14### `setCurrentlyLoadingFileTest(test)`15### `setCurrentlyLoadingFileFixture(fixture)`
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!!