Best JavaScript code snippet using playwright-internal
plugin.spec.js
Source: plugin.spec.js
...3import { babelTransform, importSyntaxPlugin } from './babel-helpers';4describe('Babel Root Import - Plugin', () => {5 it('transforms the relative path into an absolute path', () => {6 const targetRequire = slash(`/some/example.js`);7 const transformedImport = babelTransform(8 "import SomeExample from '~/some/example.js';",9 {10 plugins: [BabelRootImportPlugin],11 },12 );13 const transformedRequire = babelTransform(14 "var SomeExample = require('~/some/example.js');",15 {16 plugins: [BabelRootImportPlugin],17 },18 );19 const transformedRequireResolve = babelTransform(20 "var SomeExample = require.resolve('~/some/example.js');",21 {22 plugins: [BabelRootImportPlugin],23 },24 );25 expect(transformedImport.code).to.contain(targetRequire);26 expect(transformedRequire.code).to.contain(targetRequire);27 expect(transformedRequireResolve.code).to.contain(targetRequire);28 });29 it('transforms for import() syntax', () => {30 const targetRequire = slash(`"./some/example.js"`);31 const transformed = babelTransform(32 'var SomeExample = import("~/some/example.js");',33 {34 plugins: [importSyntaxPlugin, BabelRootImportPlugin],35 },36 );37 expect(transformed.code).to.contain(targetRequire);38 });39 it('transforms for import() syntax with template literal', () => {40 const targetRequire = slash('`./some/${foo}`');41 const transformed = babelTransform('var SomeExample = import(`~/some/${foo}`);', {42 plugins: [importSyntaxPlugin, BabelRootImportPlugin],43 });44 expect(transformed.code).to.contain(targetRequire);45 });46 it('transforms for require() with template literal', () => {47 const targetRequire = slash('`./some/${foo}`');48 const transformed = babelTransform(49 'var SomeExample = require(`~/some/${foo}`);',50 {51 plugins: [BabelRootImportPlugin],52 },53 );54 expect(transformed.code).to.contain(targetRequire);55 });56 it('transforms for custom functions', () => {57 const targetRequire = slash(`/some/example.js`);58 const transformed = babelTransform(59 "var SomeExample = jest.mock('~/some/example.js');",60 {61 plugins: [62 [63 BabelRootImportPlugin,64 {65 functions: ['jest.mock'],66 },67 ],68 ],69 },70 );71 expect(transformed.code).to.contain(targetRequire);72 });73 it('transforms the relative path into an absolute path with the configured root-path', () => {74 const targetRequire = slash('/some/custom/root/some/example.js');75 const transformedImport = babelTransform(76 "import SomeExample from '~/some/example.js';",77 {78 plugins: [79 [80 BabelRootImportPlugin,81 {82 rootPathSuffix: 'some/custom/root',83 },84 ],85 ],86 },87 );88 const transformedRequire = babelTransform(89 "var SomeExample = require('~/some/example.js');",90 {91 plugins: [92 [93 BabelRootImportPlugin,94 {95 rootPathSuffix: 'some/custom/root',96 },97 ],98 ],99 },100 );101 expect(transformedImport.code).to.contain(targetRequire);102 expect(transformedRequire.code).to.contain(targetRequire);103 });104 it('transforms the relative paths into an absolute paths with the configured root-paths', () => {105 const paths = [106 {107 rootPathPrefix: '~',108 rootPathSuffix: 'some1/custom/root',109 },110 {111 rootPathPrefix: '@',112 rootPathSuffix: 'some2/custom/root',113 },114 ];115 const pluginConfig = process.env.BABEL_VERSION === '7' ? { paths } : paths;116 const plugins = [[BabelRootImportPlugin, pluginConfig]];117 const targetRequire1 = slash(`/some1/custom/root/some/example.js`);118 const transformedImport1 = babelTransform(119 "import SomeExample from '~/some/example.js';",120 {121 plugins,122 },123 );124 const transformedRequire1 = babelTransform(125 "var SomeExample = require('~/some/example.js');",126 {127 plugins,128 },129 );130 const targetRequire2 = slash(`/some2/custom/root/some/example.js`);131 const transformedImport2 = babelTransform(132 "import SomeExample from '@/some/example.js';",133 {134 plugins,135 },136 );137 const transformedRequire2 = babelTransform(138 "var SomeExample = require('@/some/example.js');",139 {140 plugins,141 },142 );143 expect(transformedImport1.code).to.contain(targetRequire1);144 expect(transformedRequire1.code).to.contain(targetRequire1);145 expect(transformedImport2.code).to.contain(targetRequire2);146 expect(transformedRequire2.code).to.contain(targetRequire2);147 });148 it('uses the "@" as custom prefix to detect a root-import path', () => {149 const targetRequire = slash(`/some/example.js`);150 const transformedImport = babelTransform(151 "import SomeExample from '@/some/example.js';",152 {153 plugins: [154 [155 BabelRootImportPlugin,156 {157 rootPathPrefix: '@',158 },159 ],160 ],161 },162 );163 const transformedRequire = babelTransform(164 "var SomeExample = require('@/some/example.js');",165 {166 plugins: [167 [168 BabelRootImportPlugin,169 {170 rootPathPrefix: '@',171 },172 ],173 ],174 },175 );176 expect(transformedImport.code).to.contain(targetRequire);177 expect(transformedRequire.code).to.contain(targetRequire);178 });179 it('supports re-export syntax (export * from ... or export { named } from ...)', () => {180 const targetRequire = slash(`/some/example.js`);181 const transformedExportAll = babelTransform(182 "export * from '@/some/example.js';",183 {184 plugins: [185 [186 BabelRootImportPlugin,187 {188 rootPathPrefix: '@',189 },190 ],191 ],192 },193 );194 const transformedExportNamed = babelTransform(195 "export { named } from '@/some/example.js';",196 {197 plugins: [198 [199 BabelRootImportPlugin,200 {201 rootPathPrefix: '@',202 },203 ],204 ],205 },206 );207 expect(transformedExportNamed.code).to.contain(targetRequire);208 expect(transformedExportAll.code).to.contain(targetRequire);209 });210 it('uses the "/" as custom prefix to detect a root-import path', () => {211 const targetRequire = slash(`/some/example.js`);212 const transformedImport = babelTransform(213 "import SomeExample from '/some/example.js';",214 {215 plugins: [216 [217 BabelRootImportPlugin,218 {219 rootPathPrefix: '/',220 },221 ],222 ],223 },224 );225 const transformedRequire = babelTransform(226 "var SomeExample = require('/some/example.js');",227 {228 plugins: [229 [230 BabelRootImportPlugin,231 {232 rootPathPrefix: '/',233 },234 ],235 ],236 },237 );238 expect(transformedImport.code).to.contain(targetRequire);239 expect(transformedRequire.code).to.contain(targetRequire);240 });241 it('uses the "â" as custom prefix to detect a root-import path', () => {242 const targetRequire = slash(`/some/example.js`);243 const transformedImport = babelTransform(244 "import SomeExample from '-/some/example.js';",245 {246 plugins: [247 [248 BabelRootImportPlugin,249 {250 rootPathPrefix: '-',251 },252 ],253 ],254 },255 );256 const transformedRequire = babelTransform(257 "var SomeExample = require('-/some/example.js');",258 {259 plugins: [260 [261 BabelRootImportPlugin,262 {263 rootPathPrefix: '-',264 },265 ],266 ],267 },268 );269 expect(transformedImport.code).to.contain(targetRequire);270 expect(transformedRequire.code).to.contain(targetRequire);271 });272 it('uses "@" as custom prefix to detect a root-import path and has a custom rootPathSuffix', () => {273 const targetRequire = slash(`/some/example.js`);274 const transformedImport = babelTransform(275 "import SomeExample from '@/example.js';",276 {277 plugins: [278 [279 BabelRootImportPlugin,280 {281 rootPathPrefix: '@',282 rootPathSuffix: 'some',283 },284 ],285 ],286 },287 );288 const transformedRequire = babelTransform(289 "var SomeExample = require('@/example.js');",290 {291 plugins: [292 [293 BabelRootImportPlugin,294 {295 rootPathPrefix: '@',296 rootPathSuffix: 'some',297 },298 ],299 ],300 },301 );302 expect(transformedImport.code).to.contain(targetRequire);303 expect(transformedRequire.code).to.contain(targetRequire);304 });305 it('transforms a multipart require path with string at the beginning', () => {306 const transformedRequire1 = babelTransform(307 "var SomeExample = require('~/some/' + 'example.js');",308 {309 plugins: [BabelRootImportPlugin],310 },311 );312 expect(transformedRequire1.code).to.be.oneOf([313 `var SomeExample = require('./some/' + 'example.js');`, // babel 6314 `var SomeExample = require("./some/" + 'example.js');`, // babel 7315 ]);316 const transformedRequire2 = babelTransform(317 "var SomeExample = require('~/some/' + 'other' + 'example.js');",318 {319 plugins: [BabelRootImportPlugin],320 },321 );322 expect(transformedRequire2.code).to.contain.oneOf([323 `var SomeExample = require('./some/' + 'other' + 'example.js');`, // babel 6324 `var SomeExample = require("./some/" + 'other' + 'example.js');`, // babel 7325 ]);326 });327 it('does not transform a multipart require path with variable at the beginning', () => {328 const targetRequire = slash(`/some' + '/example.js`);329 const transformedRequire = babelTransform(330 "var some = '~/';var SomeExample = require(some+ '/example.js');",331 {332 plugins: [BabelRootImportPlugin],333 },334 );335 expect(transformedRequire.code).to.not.contain(targetRequire);336 });337 it('Considers .. Statements in relative Paths', () => {338 const paths = [339 {340 rootPathPrefix: '~',341 rootPathSuffix: 'some1/custom/root',342 },343 {344 rootPathPrefix: '@',345 rootPathSuffix: '../../some2/custom/../custom/root',346 },347 ];348 const pluginConfig = process.env.BABEL_VERSION === '7' ? { paths } : paths;349 const plugins = [[BabelRootImportPlugin, pluginConfig]];350 const targetRequire1 = slash(`/some1/custom/root/some/example.js`);351 const transformedImport1 = babelTransform(352 "import SomeExample from '~/some/example.js';",353 {354 plugins,355 },356 );357 const transformedRequire1 = babelTransform(358 "var SomeExample = require('~/some/example.js');",359 {360 plugins,361 },362 );363 const targetRequire2 = slash(`../../some2/custom/root/some/example.js`);364 const transformedImport2 = babelTransform(365 "import SomeExample from '@/some/example.js';",366 {367 plugins,368 },369 );370 const transformedRequire2 = babelTransform(371 "var SomeExample = require('@/some/example.js');",372 {373 plugins,374 },375 );376 expect(transformedImport1.code).to.contain(targetRequire1);377 expect(transformedRequire1.code).to.contain(targetRequire1);378 expect(transformedImport2.code).to.contain(targetRequire2);379 expect(transformedRequire2.code).to.contain(targetRequire2);380 });...
test.js
Source: test.js
2const assert = require('chai').assert;3const getErrorMessage = require('../lib').getErrorMessage;4const optionLabels = require('../lib').optionLabels;5const INPUT = `import 'test';`;6function babelTransform(options) {7 const babelOptions = { plugins: [ [ './lib' ] ] };8 if (options) babelOptions.plugins[0].push(options);9 return babel.transform(INPUT, babelOptions);10};11describe('Tests for options:', () => {12 it('should throw an error if there is no options parameter', () => {13 assert.throws(() => babelTransform(), getErrorMessage(0));14 });15 it('should throw an error if options parameter type is boolean', () => {16 const options = true;17 assert.throws(() => babelTransform(options), getErrorMessage(0));18 });19 it('should throw an error if options parameter is a regular expression', () => {20 const options = /.*/g;21 assert.throws(() => babelTransform(options), getErrorMessage(0));22 });23 it('should throw an error if options parameter is a number', () => {24 const options = 123;25 assert.throws(() => babelTransform(options), getErrorMessage(0));26 });27 it('should throw an error if options parameter is an empty list', () => {28 options = ''; // empty string is equal to empty list)29 assert.throws(() => babelTransform(options), getErrorMessage(0));30 });31 it('should throw an error if options parameter is an empty object', () => {32 options = {};33 assert.throws(() => babelTransform(options), getErrorMessage(0));34 });35 it('should throw an error if options item type is boolean', () => {36 const options = [ true ];37 assert.throws(() => babelTransform(options), getErrorMessage(4));38 });39 it('should throw an error if options item is a regular expression', () => {40 const options = [ /.*/g ];41 assert.throws(() => babelTransform(options), getErrorMessage(4));42 });43 it('should throw an error if options item is a string', () => {44 const options = [ 'test' ];45 assert.throws(() => babelTransform(options), getErrorMessage(4));46 });47 it('should throw an error if options item is a number', () => {48 const options = [ 123 ];49 assert.throws(() => babelTransform(options), getErrorMessage(4));50 });51 it('should throw an error if options item is a list', () => {52 const options = [ [] ];53 assert.throws(() => babelTransform(options), getErrorMessage(4));54 });55 it('should throw an error if «test» option is missing', () => {56 const options = [ {} ];57 assert.throws(() => babelTransform(options), getErrorMessage(1, optionLabels.test));58 });59 it('should throw an error if «test» option is an empty list', () => {60 const options = [ { test: [] } ];61 assert.throws(() => babelTransform(options), getErrorMessage(1, optionLabels.test));62 });63 it('should throw an error if «test» option is an empty object', () => {64 const options = [ { test: {} } ];65 assert.throws(() => babelTransform(options), getErrorMessage(1, optionLabels.test));66 });67 it('should throw an error if «test» option type is boolean', () => {68 const options = [ { test: true } ];69 assert.throws(() => babelTransform(options), getErrorMessage(1, optionLabels.test));70 });71 it('should throw an error if «test» option is a number', () => {72 const options = [ { test: 123 } ];73 assert.throws(() => babelTransform(options), getErrorMessage(1, optionLabels.test));74 });75 it('should throw an error if «test» option is a string', () => {76 const options = [ { test: 'test'} ];77 assert.throws(() => babelTransform(options), getErrorMessage(2, optionLabels.test));78 });79 it('should throw an error if «test» option is an object', () => {80 const options = [ { test: { one: 1 } } ];81 assert.throws(() => babelTransform(options), getErrorMessage(2, optionLabels.test));82 });83 it('should throw an error if «replacer» option is missing', () => {84 const options = [ { test: /.*/g } ];85 assert.throws(() => babelTransform(options), getErrorMessage(1, optionLabels.replacer));86 });87 it('should throw an error if «replacer» option is an empty list', () => {88 const options = [ { test: /.*/g, replacer: [] } ];89 assert.throws(() => babelTransform(options), getErrorMessage(1, optionLabels.replacer));90 });91 it('should throw an error if «replacer» option is an empty object', () => {92 const options = [ { test: /.*/g, replacer: {} } ];93 assert.throws(() => babelTransform(options), getErrorMessage(1, optionLabels.replacer));94 });95 it('should throw an error if «replacer» option is a regular expression', () => {96 const options = [ { test: /.*/g, replacer: /.*/g } ];97 assert.throws(() => babelTransform(options), getErrorMessage(1, optionLabels.replacer));98 });99 it('should throw an error if «replacer» option is an object', () => {100 const options = [ { test: /.*/g, replacer: { one: 1 } } ];101 assert.throws(() => babelTransform(options), getErrorMessage(3, optionLabels.replacer));102 });103 it('should throw an error if «replacer» option type is boolean', () => {104 const options = [ { test: /.*/g, replacer: true } ];105 assert.throws(() => babelTransform(options), getErrorMessage(1, optionLabels.replacer));106 });107 it('should throw an error if «replacer» option is a number', () => {108 const options = [ { test: /.*/g, replacer: 123 } ];109 assert.throws(() => babelTransform(options), getErrorMessage(1, optionLabels.replacer));110 });111 it('should pass if «replacer» option is a function', () => {112 const options = [ { test: /.+/g, replacer: match => { return match } } ];113 assert.equal(babelTransform(options).code, INPUT);114 });115});116function getBabelTransformCode(input, options) {117 const babelOptions = { plugins: [ [ './lib' ] ] };118 babelOptions.plugins[0].push(options);119 return babel.transform(input, babelOptions).code;120};121describe('Functionality tests:', () => {122 it('only one replacement rule should be processed', () => {123 const input = `import styl from '../stylus/common.styl';`;124 const expected = `import styl from '../sass/common.styl';`;125 const options = [126 { test: /\/stylus\//, replacer: '/sass/' },127 { test: /\.styl/i, replacer: '$&?theme-red' }...
babel-transform.js
Source: babel-transform.js
1"use strict";2var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {3 if (k2 === undefined) k2 = k;4 var desc = Object.getOwnPropertyDescriptor(m, k);5 if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {6 desc = { enumerable: true, get: function() { return m[k]; } };7 }8 Object.defineProperty(o, k2, desc);9}) : (function(o, m, k, k2) {10 if (k2 === undefined) k2 = k;11 o[k2] = m[k];12}));13var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {14 Object.defineProperty(o, "default", { enumerable: true, value: v });15}) : function(o, v) {16 o["default"] = v;17});18var __importStar = (this && this.__importStar) || function (mod) {19 if (mod && mod.__esModule) return mod;20 var result = {};21 if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);22 __setModuleDefault(result, mod);23 return result;24};25var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {26 if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {27 if (ar || !(i in from)) {28 if (!ar) ar = Array.prototype.slice.call(from, 0, i);29 ar[i] = from[i];30 }31 }32 return to.concat(ar || Array.prototype.slice.call(from));33};34Object.defineProperty(exports, "__esModule", { value: true });35exports.babelTransformExpression = exports.babelTransformCode = exports.babelTransform = void 0;36var babel = __importStar(require("@babel/core"));37var lodash_1 = require("lodash");38var jsxPlugin = require('@babel/plugin-syntax-jsx');39var tsPreset = require('@babel/preset-typescript');40var decorators = require('@babel/plugin-syntax-decorators');41var babelTransform = function (code, visitor) {42 return babel.transform(code, {43 sourceFileName: 'file.tsx',44 configFile: false,45 babelrc: false,46 presets: [[tsPreset, { isTSX: true, allExtensions: true }]],47 plugins: __spreadArray([48 [decorators, { legacy: true }],49 jsxPlugin50 ], (visitor ? [function () { return ({ visitor: visitor }); }] : []), true),51 });52};53exports.babelTransform = babelTransform;54var babelTransformCode = function (code, visitor) {55 var _a;56 return ((_a = (0, exports.babelTransform)(code, visitor)) === null || _a === void 0 ? void 0 : _a.code) || '';57};58exports.babelTransformCode = babelTransformCode;59var babelTransformExpression = function (code, visitor, type) {60 var _a;61 if (type === void 0) { type = 'unknown'; }62 if (!code) {63 return '';64 }65 // match for object literal like { foo: ... }66 if (type === 'unknown' && code.trim().match(/^\s*{\s*[a-z0-9]+:/i)) {67 type = 'expression';68 }69 // For Builder content70 if (type === 'unknown' &&71 (code.includes('return _virtual_index') ||72 code.trim().startsWith('return ')) &&73 !code.trim().startsWith('function')) {74 type = 'functionBody';75 }76 var useCode = code;77 if (type === 'functionBody') {78 useCode = "function(){".concat(useCode, "}");79 }80 var result = type === 'expression'81 ? null82 : (0, lodash_1.attempt)(function () {83 var _a;84 var result = ((_a = (0, exports.babelTransform)(useCode, visitor)) === null || _a === void 0 ? void 0 : _a.code) || '';85 if (type === 'functionBody') {86 return result.replace(/^function\(\)\{/, '').replace(/\};$/, '');87 }88 else {89 // Babel addes trailing semicolons, but for expressions we need those gone90 // TODO: maybe detect if the original code ended with one, and keep it if so, for the case91 // of appending several fragements92 return result.replace(/;$/, '');93 }94 });95 if ((0, lodash_1.isError)(result) || type === 'expression') {96 try {97 // If it can't, e.g. this is an expression or code fragment, modify the code below and try again98 // Detect method fragments. These get passed sometimes and otherwise99 // generate compile errors. They are of the form `foo() { ... }`100 var isMethod = Boolean(!code.startsWith('function') &&101 code.match(/^[a-z0-9]+\s*\([^\)]*\)\s*[\{:]/i));102 if (isMethod) {103 useCode = "function ".concat(useCode);104 }105 // Parse the code as an expression (instead of the default, a block) by giving it a fake variable assignment106 // e.g. if the code parsed is { ... } babel will treat that as a block by deafult, unless processed as an expression107 // that is an object108 useCode = "let _ = ".concat(useCode);109 result = (((_a = (0, exports.babelTransform)(useCode, visitor)) === null || _a === void 0 ? void 0 : _a.code) || '')110 // Babel addes trailing semicolons, but for expressions we need those gone111 .replace(/;$/, '')112 // Remove our fake variable assignment113 .replace(/let _ =\s/, '');114 if (isMethod) {115 result = result.replace('function', '');116 }117 }118 catch (err) {119 console.error('Error parsing code:\n', code, '\n', result);120 try {121 return (0, exports.babelTransformExpression)(code, visitor, 'functionBody');122 }123 catch (err) {124 throw err;125 }126 }127 }128 if (type === 'functionBody') {129 return result.replace(/^function\s*\(\)\s*\{/, '').replace(/\};?$/, '');130 }131 else {132 // Babel addes trailing semicolons, but for expressions we need those gone133 // TODO: maybe detect if the original code ended with one, and keep it if so, for the case134 // of appending several fragements135 return result.replace(/;$/, '');136 }137};...
compile.js
Source: compile.js
1console.log("loading libs...");2var args = require("minimist")(3 process.argv.slice(2),4 {5 default : {6 transforms: null7 }8 }9);10// console.log(args);11// return;12var browserify = require("browserify");13var babelify = require("babelify");14// var stringify = require("stringify");15var fs = require("fs");16var uglify = require("uglify-js");17var sass = require("node-sass");18var footer = "\nconsole.log('Build Time: ', '" + (new Date()).toString() + "');";19var babelTransform = [20 [21 babelify,22 {23 loose: 'all',24 stage: 0,25 optional: 'runtime',26 blacklist: "flow",27 compact: false,28 ignore: /(lib|node_modules)\/.*/29 }30 ]31];32if (args.transforms !== null) {33 babelTransform = babelTransform.concat(require(args.transforms));34}35var settings = {36 entries: ["./" + args.source + ".js"],37 debug: true,38 paths: ['./js'],39 transform: babelTransform,40 extensions: [".js"]41};42switch (args.type) {43 case 'js': {44 var compiler = browserify(settings);45 if (args.hasOwnProperty('exclude') === true) {46 if (typeof args.exclude === 'string') {47 compiler.exclude(args.exclude);48 } else {49 args.exclude.forEach(function (exclusion) {50 compiler.exclude(exclusion);51 });52 }53 }54 console.log("compiling code...");55 compiler.bundle(function (err, buffer) {56 if (err !== null) {57 return;58 }59 if (args.minify === true) {60 console.log("minifying code...");61 var code = buffer.toString();62 var minified = uglify.minify(code, {fromString: true});63 buffer = minified.code;64 }65 console.log("saving compiled code...");66 // buffer.write(footer);67 var outputFile = args.dest + ".js";68 fs.writeFile(69 outputFile,70 buffer,71 {encoding: 'utf8'},72 function () {73 if (args.buildTime === true) {74 fs.appendFile(outputFile, footer, {encoding: 'utf8'});75 }76 console.log("Finished at", new Date());77 }78 );79 }).on(80 'error',81 function (error) {82 console.log(error.toString());83 }84 );85 break;86 }87 case 'css': {88 console.log("compiling css...");89 sass.render(90 {91 file: args.source + '.sass'92 },93 function (err, result) {94 if (err !== null) {95 console.log(err.message);96 console.log(err.file, "@line", err.line, 'column', err.column);97 return;98 }99 console.log("saving css...");100 fs.writeFile(101 args.dest + '.css',102 result.css,103 {encoding: 'utf8'},104 function () {105 console.log("Done");106 }107 );108 }109 );110 break;111 }...
scripts.js
Source: scripts.js
1module.exports = function(gulp, config) {2 return function(done) {3 if(!config.scripts) return done()4 var c = require('better-console')5 c.info('~ scripts')6 var babel = require('babel-core')7 var replace = require('gulp-replace')8 var uglify = require('gulp-uglify')9 var webmake = require('gulp-webmake')10 var babelTransform = function(code, opts){11 var result = babel.transform(code, {12 sourceMap: config.devmode,13 filename: opts.localFilename,14 highlightCode: false15 })16 return { code: result.code, sourceMap: JSON.stringify(result.map) }17 }18 var task = gulp.src(config.scripts, { base: config.src_folder })19 task = task.pipe(webmake({20 'ext': [21 'coffee',22 { name: 'BabelJSX', extension: 'jsx', type: 'js', compile: babelTransform },23 { name: 'BabelES6', extension: 'es6', type: 'js', compile: babelTransform },24 { name: 'BabelES', extension: 'es', type: 'js', compile: babelTransform }25 ],26 'sourceMap': config.devmode,27 'cache': config.devmode28 }))29 .pipe(replace(/process\.env\.NODE_ENV/g, config.devmode ? "'development'" : "'production'")) // do simple envify30 .pipe(replace('DEBUG', config.devmode ? 'true' : 'false')) // inject DEBUG variable31 if(config.uglify !== false){32 var uglifyOptions = (typeof config.uglify == 'object') ? config.uglify : {}33 task = task.pipe(uglify(uglifyOptions))34 }35 return task.pipe(gulp.dest(config.dist_folder))36 }...
babel.js
Source: babel.js
...11 ast: false,12 filename,13 }14 try {15 return babelTransform(input, babelConfig).code;16 } catch (ex) {17 // Parsing stack is extremely long and not very useful, so just rethrow the message.18 throw new Error(ex.message);19 }20}21export function ReactNET_transform_sourcemap(input, babelConfig, filename) {22 babelConfig = {23 ...JSON.parse(babelConfig),24 ast: false,25 filename,26 sourceMaps: true,27 };28 try {29 var result = babelTransform(input, babelConfig);30 return JSON.stringify({31 babelVersion,32 code: result.code,33 sourceMap: result.map34 });35 } catch (ex) {36 // Parsing stack is extremely long and not very useful, so just rethrow the message.37 throw new Error(ex.message);38 }...
class-test.js
Source: class-test.js
...6 t.plan(1);7 let path = './tests/post-babel-classes/class.jsx';8 var dir = dirname(path);9 let source = readFileSync(path);10 let code = babelTransform(source, false, {11 blacklist: [12 'react',13 'es6.modules'14 ]15 });16 t.equal(compileTemplate(customRequire(dir, babelTransform(code)))(), react(path));17});18test('classes without default-props should be able to use if babel already transformed syntax', (t) => {19 t.plan(1);20 let path = './tests/post-babel-classes/class-without-default-props.jsx';21 var dir = dirname(path);22 let source = readFileSync(path);23 let code = babelTransform(source, false, {24 blacklist: [25 'react',26 'es6.modules'27 ]28 });29 t.equal(compileTemplate(customRequire(dir, babelTransform(code)))(), react(path));...
babel-worker.js
Source: babel-worker.js
...6var babelTransformDynamicImport = require('babel-plugin-syntax-dynamic-import');7var babelTransformES2015ModulesSystemJS = require('babel-plugin-transform-es2015-modules-systemjs');8self.onmessage = function (evt) {9 // transform source with Babel10 var output = babelTransform(evt.data.source, {11 compact: false,12 filename: evt.data.key + '!transpiled',13 sourceFileName: evt.data.key,14 moduleIds: false,15 sourceMaps: 'inline',16 babelrc: false,17 plugins: [babelTransformDynamicImport, babelTransformES2015ModulesSystemJS],18 });19 self.postMessage({key: evt.data.key, code: output.code, source: evt.data.source});...
Using AI Code Generation
1const playwright = require('playwright');2(async () => {3 for (const browserType of BROWSER) {4 const browser = await playwright[browserType].launch();5 const context = await browser.newContext();6 const page = await context.newPage();7 const output = await page.evaluate(async () => {8 const { babelTransform } = window['playwright'].internal;9 const { code, map } = await babelTransform('const a = 1', {10 });11 return { code, map };12 });13 console.log(output);14 await browser.close();15 }16})();17{ code: '"use strict";18var a = 1;',19 map: undefined }
Using AI Code Generation
1const { Playwright } = require('playwright-core');2const { chromium } = require('playwright-chromium');3const { firefox } = require('playwright-firefox');4const { webkit } = require('playwright-webkit');5(async () => {6 const browser = await chromium.launch();7 const page = await browser.newPage();8 await page.screenshot({ path: 'example.png' });9 await browser.close();10})();11const { Playwright } = require('playwright-core');12const { chromium } = require('playwright-chromium');13const { firefox } = require('playwright-firefox');14const { webkit } = require('playwright-webkit');15(async () => {16 const browser = await chromium.launch();17 const page = await browser.newPage();18 await page.screenshot({ path: 'example.png' });19 await browser.close();20})();21const { Playwright } = require('playwright-core');22const { chromium } = require('playwright-chromium');23const { firefox } = require('playwright-firefox');24const { webkit } = require('playwright-webkit');25(async () => {26 const browser = await chromium.launch();27 const page = await browser.newPage();28 await page.screenshot({ path: 'example.png' });29 await browser.close();30})();31const { Playwright } = require('playwright-core');32const { chromium } = require('playwright-chromium');33const { firefox } = require('playwright-firefox');34const { webkit } = require('playwright-webkit');35(async () => {36 const browser = await chromium.launch();37 const page = await browser.newPage();38 await page.screenshot({ path: 'example.png' });39 await browser.close();40})();41const { Playwright } = require('playwright-core');42const { chromium } = require('playwright
Using AI Code Generation
1const {chromium} = require('playwright');2const {babelTransform} = require('playwright/lib/server/supplements/recorder/recorderSupplement.js');3const fs = require('fs');4const path = require('path');5(async () => {6 const browser = await chromium.launch();7 const page = await browser.newPage();8 await page.click('text="I agree"');9 await page.click('text="Google apps"');10 await page.click('text="Gmail"');11 await page.click('text="Sign in"');12 await page.click('css=[aria-label="Email or phone"] >> nth=1');13 await page.fill('css=[aria-label="Email or phone"] >> nth=1', '
Using AI Code Generation
1const playwright = require('playwright');2const { babelTransform } = require('playwright/lib/server/inspector');3(async () => {4 const browser = await playwright.chromium.launch();5 const context = await browser.newContext();6 const page = await context.newPage();7 await page.evaluate(() => {8 const babelTransform = window['playwright'].babelTransform;9 const { code, map, ast } = babelTransform('2*3', { presets: ['env'] });10 console.log(code);11 });12 await browser.close();13})();14 Edge: Spartan (44.19041.423.0), Chromium (87.0.664.66)15const playwright = require('playwright');16const { babelTransform } = require('playwright/lib/server/inspector');17(async () => {18 const browser = await playwright.chromium.launch();19 const context = await browser.newContext();20 const page = await context.newPage();21 await page.evaluate(() => {
Using AI Code Generation
1const path = require('path');2const playwright = require('playwright');3const babel = require('@babel/core');4const { Internal } = playwright;5const { babelTransform } = Internal;6import { test } from 'playwright';7test('test', async ({ page }) => {8 await page.screenshot({ path: 'example.png' });9});10`;11const result = babelTransform(source, {12 path.join(__dirname, '../node_modules/@babel/preset-env'),13 path.join(__dirname, '../node_modules/@babel/preset-typescript'),14 path.join(__dirname, '../node_modules/babel-plugin-transform-async-to-promises/helpers'),15 path.join(__dirname, '../node_modules/babel-plugin-transform-regenerator'),16 path.join(__dirname, '../node_modules/babel-plugin-syntax-async-generators'),17 path.join(__dirname, '../node_modules/babel-plugin-syntax-object-rest-spread'),18 path.join(__dirname, '../node_modules/babel-plugin-syntax-top-level-await'),19 path.join(__dirname, '../node_modules/babel-plugin-transform-async-to-generator'),20 path.join(__dirname, '../node_modules/babel-plugin-transform-classes'),21 path.join(__dirname, '../node_modules/babel-plugin-transform-destructuring'),22 path.join(__dirname, '../node_modules/babel-plugin-transform-dotall-regex'),23 path.join(__dirname, '../node_modules/babel-plugin-transform-exponentiation-operator'),24 path.join(__dirname, '../node_modules/babel-plugin-transform-for-of'),25 path.join(__dirname, '../node_modules/babel-plugin-transform-function-name'),26 path.join(__dirname, '../node_modules/babel-plugin-transform-literals'),27 path.join(__dirname, '../node_modules/babel-plugin-transform-modules-commonjs'),28 path.join(__dirname, '../node_modules/babel-plugin-transform-object-assign'),29 path.join(__dirname, '../node_modules/babel-plugin-transform-object-rest-spread'),30 path.join(__dirname, '../node_modules/babel-plugin-transform-parameters'),31 path.join(__dirname, '../node_modules/babel-plugin-transform-regenerator'),32 path.join(__dirname, '../node_modules/babel-plugin-transform-shorthand-properties'),33 path.join(__dirname, '../node_modules/babel-plugin-transform-spread'),
Using AI Code Generation
1const { PlaywrightTransform } = require('playwright-transform');2const playwrightTransform = new PlaywrightTransform();3const transformedCode = await playwrightTransform.babelTransform('const foo = "bar"');4const { PlaywrightTransform } = require('playwright-transform');5const playwrightTransform = new PlaywrightTransform();6const transformedCode = await playwrightTransform.playwrightTransform('const foo = "bar"');7const { PlaywrightTransform } = require('playwright-transform');8const playwrightTransform = new PlaywrightTransform();9const transformedCode = await playwrightTransform.playwrightTransform('const foo = "bar"');10const { PlaywrightTransform } = require('playwright-transform');11const playwrightTransform = new PlaywrightTransform();12const transformedCode = await playwrightTransform.playwrightTransform('const foo = "bar"');13const { PlaywrightTransform } = require('playwright-transform');14const playwrightTransform = new PlaywrightTransform();15const transformedCode = await playwrightTransform.playwrightTransform('const foo = "bar"');16const { PlaywrightTransform } = require('playwright-transform');17const playwrightTransform = new PlaywrightTransform();18const transformedCode = await playwrightTransform.playwrightTransform('const foo = "bar"');19const { PlaywrightTransform } = require('playwright-transform');20const playwrightTransform = new PlaywrightTransform();21const transformedCode = await playwrightTransform.playwrightTransform('const foo = "bar"');22const { PlaywrightTransform } = require('playwright-transform');23const playwrightTransform = new PlaywrightTransform();24const transformedCode = await playwrightTransform.playwrightTransform('const foo = "bar"');25const { PlaywrightTransform } = require('playwright-transform');26const playwrightTransform = new PlaywrightTransform();27const transformedCode = await playwrightTransform.playwrightTransform('const foo = "bar"');28const { PlaywrightTransform } = require('playwright-transform');29const playwrightTransform = new PlaywrightTransform();
Using AI Code Generation
1const { playwrightTransform } = require('playwright');2const babel = require('@babel/core');3const fs = require('fs');4const code = fs.readFileSync('./test.js', 'utf-8');5const transformedCode = await playwrightTransform(code, {6});7fs.writeFileSync('./test-transformed.js', transformedCode);8const f = () => 42;9We welcome contributions to Playwright! Please see the [Contributing Guide](
Jest + Playwright - Test callbacks of event-based DOM library
firefox browser does not start in playwright
Is it possible to get the selector from a locator object in playwright?
How to run a list of test suites in a single file concurrently in jest?
Running Playwright in Azure Function
firefox browser does not start in playwright
This question is quite close to a "need more focus" question. But let's try to give it some focus:
Does Playwright has access to the cPicker object on the page? Does it has access to the window object?
Yes, you can access both cPicker and the window object inside an evaluate call.
Should I trigger the events from the HTML file itself, and in the callbacks, print in the DOM the result, in some dummy-element, and then infer from that dummy element text that the callbacks fired?
Exactly, or you can assign values to a javascript variable:
const cPicker = new ColorPicker({
onClickOutside(e){
},
onInput(color){
window['color'] = color;
},
onChange(color){
window['result'] = color;
}
})
And then
it('Should call all callbacks with correct arguments', async() => {
await page.goto(`http://localhost:5000/tests/visual/basic.html`, {waitUntil:'load'})
// Wait until the next frame
await page.evaluate(() => new Promise(requestAnimationFrame))
// Act
// Assert
const result = await page.evaluate(() => window['color']);
// Check the value
})
Check out the latest blogs from LambdaTest on this topic:
Native apps are developed specifically for one platform. Hence they are fast and deliver superior performance. They can be downloaded from various app stores and are not accessible through browsers.
One of the essential parts when performing automated UI testing, whether using Selenium or another framework, is identifying the correct web elements the tests will interact with. However, if the web elements are not located correctly, you might get NoSuchElementException in Selenium. This would cause a false negative result because we won’t get to the actual functionality check. Instead, our test will fail simply because it failed to interact with the correct element.
Smartphones have changed the way humans interact with technology. Be it travel, fitness, lifestyle, video games, or even services, it’s all just a few touches away (quite literally so). We only need to look at the growing throngs of smartphone or tablet users vs. desktop users to grasp this reality.
As part of one of my consulting efforts, I worked with a mid-sized company that was looking to move toward a more agile manner of developing software. As with any shift in work style, there is some bewilderment and, for some, considerable anxiety. People are being challenged to leave their comfort zones and embrace a continuously changing, dynamic working environment. And, dare I say it, testing may be the most ‘disturbed’ of the software roles in agile development.
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!!