Best JavaScript code snippet using playwright-internal
TestReport.jsx
Source: TestReport.jsx
...127 return "";128 }129 const [ text ] = msg,130 [ ex, filePos ] = text.split( "\n" ),131 errMessage = TestReport.removeAnsiColors( ex.length > 10 ? ex : text );132 filePos && this.parseReportFailureLocationLine( filePos.trim(), errMessage.substr( 0, 80 ) );133 return errMessage;134 }135 /**-136 * Parse report lines like:137 * "at Object.somecrpa (/tmp/.runtime-test/specs/react-html5-form-valid.spec.js:46:7)"138 * @param String filePos139 * @param String message140 */141 parseReportFailureLocationLine( filePos, message ) {142 const re = /\((.*):(\d+):(\d+)\)$/,143 match = filePos.match( re );144 if ( !match ) {145 return;146 }147 const file = match[ 1 ],148 line = match[ 2 ];149 if ( !( file in this.reportedFailures ) ) {150 this.reportedFailures[ file ] = [];151 }152 this.reportedFailures[ file ].push({153 line,154 message155 });156 }157 /*eslint no-control-regex: 0*/158 static removeAnsiColors( msg ) {159 const re = /[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g;160 return msg.replace( re, "" );161 }162 getDetails( testResults ) {163 // report.results.testResults164 return testResults.reduce( ( payload, entry ) => {165 // testResultItem: { console, failureMessage, leaks, numFailingTests, numPassingTests, numPendingTests,166 // perfStats, skipped, snapshot, sourceMaps, testFilePath, testResults }167 const carry = entry.testResults.reduce( ( carry, test ) => {168 // test: { ancestorTitles, duration, failureMessages, fullName, location, numPassingAsserts, status, title }169 const [ suite, describe ] = test.ancestorTitles,170 suiteId = `${ suite } (${ path.parse( entry.testFilePath ).base })`;171 carry[ suiteId ] = suiteId in carry ? carry[ suiteId ] : {};172 carry[ suiteId ][ describe ] = describe in carry[ suiteId ] ? carry[ suiteId ][ describe ] : [];...
logger.test.js
Source: logger.test.js
1'use strict';2const Taste = require('@jikurata/taste');3const Logger = require('../src/Logger.js');4const Record = require('../src/Record.js');5const Console = new Logger();6Console.printMessage = false;7Taste('Emitting record event')8.test('Emits record event when a record is created', (profile) => {9 Console.on('record', (record) => {10 profile['recordEventEmitted'] = true;11 profile['record'] = record;12 });13 Console.createRecord('info','foobar');14 Console.unregisterEvent('record');15})16.expect('recordEventEmitted').toBeTruthy()17.expect('record').toBeInstanceOf(Record);18Taste('Logger retains is record history')19.test('Logger creates a Record object and stores it in its history', (profile) => {20 Console.history.length = 0;21 Console.log('testing log history');22 Console.info('testing log history');23 Console.warn('testing log history');24 Console.error('testing log history');25 profile['logHistoryLength'] = Console.history.length;26})27.expect('logHistoryLength').toEqual(4);28 29Taste('Logger history limit')30.test('Logger deletes the oldest entries if past limit', (profile) => {31 Console.historyLimit = 3;32 for ( let i = 6; --i; ) Console.info(i);33 profile['restrictedHistoryLength'] = Console.history.length;34})35.expect('restrictedHistoryLength').toEqual(3);36Taste('Identifying data types')37.test(profile => {38 class Foo {39 constructor() {40 this.value = 'bar';41 }42 }43 profile.isNull = Console.getDataType(null);44 profile.isUndefined = Console.getDataType(undefined);45 profile.isBoolean = Console.getDataType(true);46 profile.isString = Console.getDataType('foobar');47 profile.isNumber = Console.getDataType(1);48 profile.isBigInt = Console.getDataType(1n);49 profile.isFunction = Console.getDataType(() => {});50 profile.isSymbol = Console.getDataType(Symbol('foo'));51 profile.isObject1 = Console.getDataType({1: 'foo', 2: 'bar'});52 profile.isObject2 = Console.getDataType([1,2,3]);53 profile.isObject3 = Console.getDataType(new Foo());54})55.expect('isNull').toEqual('null')56.expect('isUndefined').toEqual('undefined')57.expect('isBoolean').toEqual('boolean')58.expect('isString').toEqual('string')59.expect('isNumber').toEqual('number')60.expect('isBigInt').toEqual('bigint')61.expect('isFunction').toEqual('function')62.expect('isSymbol').toEqual('symbol')63.expect('isObject1').toEqual('object')64.expect('isObject2').toEqual('object')65.expect('isObject3').toEqual('object');66Taste('Formatting falsy inputs')67.test(profile => {68 profile.test1 = Console.removeANSIColors(Console.log(0).colored);69 profile.test2 = Console.removeANSIColors(Console.log(-1).colored);70 profile.test3 = Console.removeANSIColors(Console.log(null).colored);71 profile.test4 = Console.removeANSIColors(Console.log(undefined).colored);72 profile.test5 = Console.removeANSIColors(Console.log(false).colored);73})74.expect('test1').toEqual('0')75.expect('test2').toEqual('-1')76.expect('test3').toEqual('null')77.expect('test4').toEqual('undefined')78.expect('test5').toEqual('false');79Taste('Formatting string inputs')80.test(profile => {81 profile.test1 = Console.removeANSIColors(Console.log('foo', 'bar').colored);82 profile.test2 = Console.removeANSIColors(Console.log('foo\nbar').colored);83 profile.test3 = Console.removeANSIColors(Console.log('').colored);84 profile.test4 = Console.removeANSIColors(Console.log('', '').colored);85 profile.test5 = Console.removeANSIColors(Console.log(' ').colored);86 profile.test6 = Console.removeANSIColors(Console.log(' ').colored);87 profile.test7 = Console.removeANSIColors(Console.log('foo' + 'bar').colored);88 profile.test8 = Console.removeANSIColors(Console.log(typeof 42).colored);89})90.expect('test1').toEqual('foo bar')91.expect('test2').toEqual('foo\nbar')92.expect('test3').toEqual('')93.expect('test4').toEqual(' ')94.expect('test6').toEqual(' ')95.expect('test7').toEqual('foobar')96.expect('test8').toEqual('number');97Taste('Formatting number inputs')98.test(profile => {99 profile.test1 = Console.removeANSIColors(Console.log(0).colored);100 profile.test2 = Console.removeANSIColors(Console.log(1).colored);101 profile.test3 = Console.removeANSIColors(Console.log(1, 2, 3).colored);102 profile.test4 = Console.removeANSIColors(Console.log(-1).colored);103 profile.test5 = Console.removeANSIColors(Console.log(40 + 2).colored);104 profile.test6 = Console.removeANSIColors(Console.log(0n).colored);105 profile.test7 = Console.removeANSIColors(Console.log(1n).colored);106})107.expect('test1').toEqual('0')108.expect('test2').toEqual('1')109.expect('test3').toEqual('1 2 3')110.expect('test4').toEqual('-1')111.expect('test5').toEqual('42')112.expect('test6').toEqual('0n')113.expect('test7').toEqual('1n');114Taste('Formatting boolean inputs')115.test(profile => {116 profile.test1 = Console.removeANSIColors(Console.log(true).colored);117 profile.test2 = Console.removeANSIColors(Console.log(3 === 3).colored);118 profile.test3 = Console.removeANSIColors(Console.log(!true).colored);119 profile.test4 = Console.removeANSIColors(Console.log(true, false).colored);120})121.expect('test1').toEqual('true')122.expect('test2').toEqual('true')123.expect('test3').toEqual('false')124.expect('test4').toEqual('true false');125Taste('Formatting array inputs')126.test(profile => {127 profile.test1 = Console.removeANSIColors(Console.log([1, 2, 3]).colored);128 profile.test2 = Console.removeANSIColors(Console.log([1, 'foo']).colored);129 profile.test3 = Console.removeANSIColors(Console.log([['a', 'b'], [1,2]]).colored);130})131.expect('test1').toEqual('[ 1, 2, 3 ]')132.expect('test2').toEqual('[ 1, \'foo\' ]')133.expect('test3').toEqual('[ [ \'a\', \'b\' ], [ 1, 2 ] ]');134Taste('Formatting symbol inputs')135.test(profile => {136 profile.test1 = Console.removeANSIColors(Console.log(Symbol(null)).colored);137 profile.test2 = Console.removeANSIColors(Console.log(Symbol(undefined)).colored);138 profile.test3 = Console.removeANSIColors(Console.log(Symbol('')).colored);139 profile.test4 = Console.removeANSIColors(Console.log(Symbol('foo')).colored);140 profile.test5 = Console.removeANSIColors(Console.log(Symbol(1)).colored);141})142.expect('test1').toEqual('Symbol(null)')143.expect('test2').toEqual('Symbol()')144.expect('test3').toEqual('Symbol()')145.expect('test4').toEqual('Symbol(foo)')146.expect('test5').toEqual('Symbol(1)');147Taste('Formatting object inputs')148.test(profile => {149 class Foo {150 constructor() {151 this.a = 1;152 this.b = '2';153 }154 }155 class Bar extends Foo {156 constructor() {157 super();158 this.c = true;159 this.d = null;160 }161 }162 profile.test1 = Console.removeANSIColors(Console.log({}).colored);163 profile.test2 = Console.removeANSIColors(Console.log({1: 'foo', a: 'bar'}).colored);164 profile.test3 = Console.removeANSIColors(Console.log({a: [1,2], b: null}).colored);165 profile.test4 = Console.removeANSIColors(Console.log(Foo).colored);166 profile.test5 = Console.removeANSIColors(Console.log(Bar).colored);167 profile.test6 = Console.removeANSIColors(Console.log(new Foo()).colored);168 profile.test7 = Console.removeANSIColors(Console.log(new Bar()).colored);169})170.expect('test1').toEqual('{ }')171.expect('test2').toEqual('{ 1: \'foo\', a: \'bar\' }')172.expect('test3').toEqual('{ a: [ 1, 2 ], b: null }')173.expect('test4').toEqual('[class Foo]')174.expect('test5').toEqual('[class Bar extends Foo]')175.expect('test6').toEqual('Foo { a: 1, b: \'2\' }')176.expect('test7').toEqual('Bar { a: 1, b: \'2\', c: true, d: null }');177Taste('Formatting function inputs')178.test(profile => {179 function foo() {}180 const bar = () => {}181 profile.test1 = Console.removeANSIColors(Console.log(foo).colored);182 profile.test2 = Console.removeANSIColors(Console.log(bar).colored);183 profile.test3 = Console.removeANSIColors(Console.log(function() {}).colored);184 profile.test4 = Console.removeANSIColors(Console.log(() => { return 'test'; }).colored);185})186.expect('test1').toEqual('[Function: foo]')187.expect('test2').toEqual('[Function: bar]')188.expect('test3').toEqual('[Function (anonymous)]')189.expect('test4').toEqual('[Function (anonymous)]');190Taste('Formatting circular references')191.test(profile => {192 class A {193 constructor() {194 this.a = 1;195 this.obj = new B(this);196 }197 }198 class B {199 constructor(ref) {200 this.b = 1;201 this.ref = ref;202 }203 }204 const arrayC = [1, 2, 3];205 const arrayD = ['a', 'b', arrayC];206 arrayC.push(arrayD);207 profile.test1 = Console.removeANSIColors(Console.log(new A()).colored);208 profile.test2 = Console.removeANSIColors(Console.log(arrayD).colored);209})210.expect('test1').toEqual('A { a: 1, obj: B { b: 1, ref: [Circular A] } }')211.expect('test2').toEqual('[ \'a\', \'b\', [ 1, 2, 3, [Circular Array] ] ]');212Taste('Formatting arrays in a log')213.test('Prints [ 1,2 ]',(profile) => {214 const a = [1,2];215 profile['formattedArray'] = Console.info(a).message;216})217.expect('formattedArray').toMatch('[ 1, 2 ]');218Taste('Formatting objects in a log')219.test('Prints { foo: 1, bar: 2 }', (profile) => {220 const o = {foo: 1, bar: 2};221 profile['formattedObject'] = Console.info(o).message;222})223.expect('formattedObject').toMatch('{ foo: 1, bar: 2 }');224Taste('Formatting multiple arguments in a log')225.test('Prints 1 2 3 and a b c', (profile) => {226 const v1 = 1;227 const v2 = 2;228 const v3 = 3;229 const v4 = 'a';230 const v5 = 'b';231 const v6 = 'c';232 profile['formattedArgs'] = Console.info(v1, v2, v3, 'and', v4, v5, v6).message;233})...
Logger.js
Source: Logger.js
1'use strict';2const EventEmitter = require('@jikurata/events');3const {format} = require('util');4const State = require('./State.js');5const Record = require('./Record.js');6let instance = null;7class Logger extends EventEmitter {8 constructor() {9 if ( instance ) return instance;10 super();11 instance = this;12 Object.defineProperty(this, 'state', {13 value: new State({14 'HISTORY_LIMIT': 50,15 'COLOR': {16 'default': '\x1b[0m',17 'boolean': '\x1b[38;5;27m',18 'number': '\x1b[38;5;64m',19 'string': '\x1b[38;5;130m',20 'text': '\x1b[38;5;250m',21 'array': '\x1b[38;5;248m',22 'object': '\x1b[38;5;248m',23 'function': '\x1b[38;5;30m',24 'bigint': '\x1b[38;5;179m', 25 'symbol': '\x1b[38;5;99m',26 'property': '\x1b[38;5;75m',27 'undefined': '\x1b[38;5;240m',28 'null': '\x1b[38;5;240m',29 'circular': '\x1b[38;5;171m',30 'info': '\x1b[38;5;28m',31 'warn': '\x1b[38;5;100m',32 'error': '\x1b[38;5;88m',33 'timestamp': '\x1b[38;5;240m'34 },35 'USE_COLORS': true,36 'PRINT_MESSAGE': true,37 'SHOW_TIMESTAMP': true,38 'SHOW_TIMEZONE': false,39 'EMIT_RECORD': true40 }),41 enumerable: true,42 writable: false,43 configurable: false44 });45 Object.defineProperty(this, 'history', {46 value: [],47 enumerable: true,48 writable: false,49 configurable: false50 });51 }52 /**53 * @param {String} type54 * @param {...Any} args 55 */56 _print(type, ...args) {57 const r = this.createRecord(type, ...args);58 this.printRecord(r);59 return r;60 }61 /**62 * @param {...Any} args63 * @returns {Record}64 */65 log(...args) {66 return this._print('info', ...args);67 }68 /**69 * @param {...Any} args70 * @returns {Record}71 */72 info(...args) {73 return this._print('info', ...args);74 }75 /**76 * @param {...Any} args77 * @returns {Record}78 */79 warn(...args) {80 return this._print('warn', ...args);81 }82 /**83 * @param {...Any} args84 * @returns {Record}85 */86 error(...args) {87 return this._print('error', ...args);88 }89 /**90 * Create a Record object91 * @param {String} type 92 * @param {...Any} args 93 * @returns {Record}94 */95 createRecord(type, ...args) {96 const t = Date.now();97 const s = this.formatColors(args);98 const record = new Record({99 type: type,100 timestamp: t,101 message: this.removeANSIColors(s),102 colored: s103 });104 // Add record to history105 this.history.push(record);106 // Remove the first entry while the current size exceeds the history limit107 let count = this.history.length - this.state.HISTORY_LIMIT;108 if ( count > 0 ) {109 for ( count; count--; ) {110 this.history.shift();111 }112 }113 if ( this.emitRecord ) {114 this.emit('record', record);115 }116 return record;117 }118 /**119 * Format a record to be printed in console120 * @param {Record} record 121 */122 printRecord(record) {123 if ( !this.printMessage ) {124 return;125 }126 let s = `# `;127 if ( this.showTimestamp ) {128 const ts = new Date(record.timestamp).toString().split(' ').slice(1, (this.showTimezone) ? 6 : 5).join(' ');129 s += `${this.getColor('timestamp')}[${ts}] `;130 }131 s += (this.useColors) ? record.colored : record.message + '\n';132 133 switch(record.type) {134 case 'info': 135 s = `${this.getColor('info')}${s}`;136 return console.info(s);137 case 'warn': 138 s = `${this.getColor('warn')}${s}`;139 return console.warn(s);140 case 'error': 141 s = `${this.getColor('error')}${s}`;142 return console.error(s);143 default: 144 s = `${this.getColor('default')}${s}`145 return console.log(s);146 }147 }148 /**149 * Stringify arguments and append color codes to data types150 * @param {Array<Any>} args151 * @returns {String} 152 */153 formatColors(args) {154 const objStack = [];155 const formatter = (arg) => {156 // Check arg's data type157 const type = this.getDataType(arg);158 const argStr = format(arg);159 if ( type === 'object' ) {160 const objectClass = (arg.constructor && arg.constructor.name) ? arg.constructor.name : '';161 // Check for cyclic references162 if ( objStack.indexOf(arg) === -1 ) {163 objStack.push(arg);164 let substr = '';165 // Format error objects166 if ( arg instanceof Error ) {167 if ( arg.stack ) {168 const split = arg.stack.split(':');169 for ( let i = 0; i < split.length; ++i ) {170 if ( i === 0 ) {171 substr += `${this.getColor('error')}`;172 }173 else if ( i === 1 ) {174 substr += `${this.getColor('text')}`;175 }176 substr += `${split[i]}:`;177 }178 }179 else {180 substr = `${this.getColor('error')}${arg.name}: ${this.getColor('text')}${arg.message}`;181 }182 }183 else if ( Array.isArray(arg) ) {184 // Format an array185 substr = `${this.getColor('array')}[ `;186 for ( let i = 0; i < arg.length; ++i ) {187 substr += `${formatter(arg[i])}`;188 substr += (i < arg.length - 1) ? `${this.getColor('array')}, ` : ' ';189 }190 substr += `${this.getColor('array')}]`;191 }192 else {193 // Format a generic object type194 substr = `${this.getColor('object')}${(objectClass && objectClass !== 'Object') ? objectClass + ' ' : ''}{ `;195 const keys = Object.keys(arg);196 for ( let i = 0; i < keys.length; ++i ) {197 const key = keys[i];198 const value = arg[key];199 substr += `${this.getColor('property')}${key}: ${formatter(value)}`;200 substr += (i < keys.length - 1) ? `${this.getColor('object')}, ` : ' ';201 }202 substr += `${this.getColor('object')}}`;203 }204 // Format complete for current object, remove from stack205 objStack.pop();206 return substr;207 }208 else {209 // Object is a cyclic reference210 return `${this.getColor('circular')}[Circular ${(objectClass)}]`;211 }212 }213 else if ( type === 'string' ) {214 // If the string is an object value, use the string color code215 if ( objStack.length ) {216 return `${this.getColor('string')}\'${argStr}${this.getColor('string')}\'`;217 }218 return `${this.getColor('text')}${argStr}`;219 }220 else {221 return `${this.getColor(type)}${argStr}`;222 }223 }224 let a = [];225 for ( let i = 0; i < args.length; ++i ) {226 a.push(formatter(args[i]));227 }228 return format(...a);229 }230 /**231 * Return the data type of arg232 * @param {Any} arg233 * @returns {String}234 */235 getDataType(arg) {236 if ( arg === null ) {237 return 'null';238 }239 else if ( arg === undefined ) {240 return 'undefined';241 }242 else if ( arg && typeof arg === 'object' ) {243 return 'object';244 }245 else {246 return typeof arg;247 }248 }249 /**250 * Get an ANSI color code for the corresponding type251 * @param {String} color 252 * @returns {String}253 */254 getColor(type) {255 return (this.state.COLOR.hasOwnProperty(type)) ? this.state.COLOR[type] : this.state.COLOR.text;256 }257 /**258 * Remove all ANSI escape attribute codes259 * @param {String} s 260 */261 removeANSIColors(s) {262 const matches = s.match(/\x1b\[[\d|;]*m/gmi);263 if ( matches ) {264 for ( let i = 0; i < matches.length; ++i ) {265 s = s.replace(matches[i], '');266 }267 }268 return s;269 }270 get historyLimit() {271 return this.state.HISTORY_LIMIT;272 }273 set historyLimit(num) {274 if ( num > -1 ) this.state.HISTORY_LIMIT = num;275 }276 get useColors() {277 return this.state.USE_COLORS;278 }279 set useColors(bool) {280 this.state.USE_COLORS = !!bool;281 }282 get printMessage() {283 return this.state.PRINT_MESSAGE;284 }285 set printMessage(bool) {286 this.state.PRINT_MESSAGE = !!bool;287 }288 get showTimestamp() {289 return this.state.SHOW_TIMESTAMP;290 }291 set showTimestamp(bool) {292 this.state.SHOW_TIMESTAMP = !!bool;293 }294 get showTimezone() {295 return this.state.SHOW_TIMEZONE;296 }297 set showTimezone(bool) {298 this.state.SHOW_TIMEZONE = !!bool;299 }300 get emitRecord() {301 return this.state.EMIT_RECORD;302 }303 set emitRecord(bool) {304 this.state.EMIT_RECORD = !!bool;305 }306}...
service.js
Source: service.js
1const { Server } = require('socket.io');2const { createServer } = require("http");3const { spawn } = require('child_process');4const httpServer = createServer();5const fs = require('fs')6const { v4: uuidv4 } = require('uuid');7const dotenv = require('dotenv');8var path = require('path');9const local_dir = './resources/temp'10dotenv.config();11spawn(12 `cd ${process.env.ELIXIR_DIR} && 13 poetry run gradualelixir configure --working-dir ${path.resolve(__dirname)}/resources/temp`, 14 { shell: true }15);16const io = new Server(httpServer, {17 cors: {18 origin: "http://localhost:3000",19 credentials: true20 }21});22const removeANSIColors = (str) => {23 return str.replace(24 /[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g,25 ''26 );27}28const events = [29 {30 name: 'typecheck static',31 command: (filename) => `cd ${process.env.ELIXIR_DIR} && poetry run gradualelixir type_check --static ${filename}`32 },33 {34 name: 'typecheck',35 command: (filename) => `cd ${process.env.ELIXIR_DIR} && poetry run gradualelixir type_check ${filename}`36 },37 {38 name: 'annotate types',39 command: (filename) => `cd ${process.env.ELIXIR_DIR} && poetry run gradualelixir type_check --annotate types ${filename}`,40 fileSubfix: '_types.ex'41 },42 {43 name: 'annotate casts',44 command: (filename) => `cd ${process.env.ELIXIR_DIR} && poetry run gradualelixir type_check --annotate casts ${filename}`,45 fileSubfix: '_casts.ex'46 }47]48io.on('connection', socket => {49 events.forEach((ev) => {50 try { 51 socket.on(ev.name, (arg) => {52 socket.emit('lock')53 const uuid = uuidv4()54 const filename = `${uuid}.ex`55 const path = `${local_dir}/${filename}`56 fs.writeFileSync(path, arg, () => {})57 const command = spawn(ev.command(filename), { shell: true });58 command.stderr.on('data', (data) => {59 socket.emit('input', {60 code: removeANSIColors(data.toString()),61 isElixir: false62 })63 })64 command.stdout.on('data', (data) => {65 if(!fs.existsSync(`${local_dir}/${uuid}${ev.fileSubfix}`)) {66 socket.emit('input', {67 code: removeANSIColors(data.toString()),68 isElixir: false69 })70 }71 })72 command.stdout.on('close', () => {73 fs.unlink(path, () => {})74 if(ev.fileSubfix) {75 const auxFile = `${local_dir}/${uuid}${ev.fileSubfix}`76 if (fs.existsSync(auxFile)) {77 const content = fs.readFileSync(auxFile, {encoding:'utf8', flag:'r'});78 socket.emit('input', {79 code: content,80 isElixir: true81 })82 fs.unlink(auxFile, () => {})83 }84 }85 socket.emit('unlock')86 })87 })88 }89 catch (err) {90 io.emit('input', err)91 socket.emit('unlock')92 }93 })94});95io.on('disconnect', () => {96 console.log('bye')97})...
status.json.js
Source: status.json.js
...23});24router.get('/', function (req, res) {25 shelljs.exec('grep "error" ' + __dirname + '/../logs/log | tail -n 1',26 function (exitcode, logOutput) {27 var lastError = utils.removeAnsiColors(logOutput);28 var lastErrorTimestamp = Math.round((new Date(lastError.split(' ')[0])).29 getTime()/1000);30 res.send(JSON.stringify({31 hostname: os.hostname(),32 uptime: os.uptime(),33 loadavg: os.loadavg(),34 totalmem: os.totalmem(),35 freemem: os.freemem(),36 processUptime: process.uptime(),37 mongoConnect: db.isConnect(),38 redisConnect: redis.status === "ready" ? true : false,39 lastError: lastError,40 lastErrorTimestamp: lastErrorTimestamp,41 gitShort: git.short,...
utils.js
Source: utils.js
1var crypto = require('crypto');2function randomToken (len) {3 if (!len) {4 len = 16;5 }6 return crypto.randomBytes(Math.ceil(len * 3 / 4))7 .toString('base64') // convert to base64 format8 .slice(0, len) // return required number of characters9 .replace(/\+/g, '0') // replace '+' with '0'10 .replace(/\//g, '0'); // replace '/' with '0'11}12exports.randomToken = randomToken;13function getRandomItem (items) {14 return items[Math.floor(Math.random()*items.length)];15}16exports.getRandomItem = getRandomItem;17function removeAnsiColors (string) {18 return string.replace(/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g, '');19}...
Using AI Code Generation
1const { removeAnsiColors } = require('playwright-core/lib/utils/terminal');2const { test, expect } = require('@playwright/test');3test('test', async ({ page }) => {4 const title = await page.innerText('.navbar__inner .navbar__title');5 expect(removeAnsiColors(title)).toBe('Playwright');6});7### `removeAnsiColors(str)`8### `removeAnsiColors.stripColor(str)`9### `removeAnsiColors.hasColor(str)`10### `removeAnsiColors.hasAnsi(str)`11### `removeAnsiColors.hasAnsiColors(str)`12### `removeAnsiColors.hasAnsiCodes(str)`13### `removeAnsiColors.hasAnsiCodesOrMarkup(str)`14### `removeAnsiColors.hasAnsiMarkup(str)`
Using AI Code Generation
1const { removeAnsiColors } = require('playwright/lib/internal/util');2const { chromium } = require('playwright');3(async () => {4 const browser = await chromium.launch();5 const context = await browser.newContext();6 const page = await context.newPage();7 const title = await page.title();8 console.log(`Title: ${removeAnsiColors(title)}`);9 await browser.close();10})();
Using AI Code Generation
1const { removeAnsiColors } = require('@playwright/test/lib/utils/terminal');2const { test } = require('@playwright/test');3test('test', async ({ page }) => {4 const title = await page.textContent('text=The most reliable end-to-end testing tool');5 console.log(title);6 console.log(removeAnsiColors(title));7});
Using AI Code Generation
1const { removeAnsiColors } = require('@playwright/test/lib/utils/terminal');2const { test } = require('@playwright/test');3const assert = require('assert');4test('removeAnsiColors', async ({}) => {5 const str = '\u001b[32mHello World';6 const result = removeAnsiColors(str);7 assert.strictEqual(result, 'Hello World');8});9 at Object.toBe (test.js:11:18)
Using AI Code Generation
1const { removeAnsiColors } = require('@playwright/test/lib/utils/terminal');2console.log(removeAnsiColors('\u001b[31mHello World!'));3### `isUnderTest()`4const { isUnderTest } = require('@playwright/test/lib/utils/utils');5console.log(isUnderTest());6### `setUnderTest()`7const { setUnderTest } = require('@playwright/test/lib/utils/utils');8setUnderTest();9### `createGuid()`10const { createGuid } = require('@playwright/test/lib/utils/utils');11console.log(createGuid());12### `createGuids()`13const { createGuids } = require('@playwright/test/lib/utils/utils');14console.log(createGuids(3));15### `isGuid()`16const { is
firefox browser does not start in playwright
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?
Jest + Playwright - Test callbacks of event-based DOM library
Running Playwright in Azure Function
I found the error. It was because of some missing libraries need. I discovered this when I downgraded playwright to version 1.9 and ran the the code then this was the error msg:
(node:12876) UnhandledPromiseRejectionWarning: browserType.launch: Host system is missing dependencies!
Some of the Universal C Runtime files cannot be found on the system. You can fix
that by installing Microsoft Visual C++ Redistributable for Visual Studio from:
https://support.microsoft.com/en-us/help/2977003/the-latest-supported-visual-c-downloads
Full list of missing libraries:
vcruntime140.dll
msvcp140.dll
Error
at Object.captureStackTrace (D:\Projects\snkrs-play\node_modules\playwright\lib\utils\stackTrace.js:48:19)
at Connection.sendMessageToServer (D:\Projects\snkrs-play\node_modules\playwright\lib\client\connection.js:69:48)
at Proxy.<anonymous> (D:\Projects\snkrs-play\node_modules\playwright\lib\client\channelOwner.js:64:61)
at D:\Projects\snkrs-play\node_modules\playwright\lib\client\browserType.js:64:67
at BrowserType._wrapApiCall (D:\Projects\snkrs-play\node_modules\playwright\lib\client\channelOwner.js:77:34)
at BrowserType.launch (D:\Projects\snkrs-play\node_modules\playwright\lib\client\browserType.js:55:21)
at D:\Projects\snkrs-play\index.js:4:35
at Object.<anonymous> (D:\Projects\snkrs-play\index.js:7:3)
at Module._compile (internal/modules/cjs/loader.js:1063:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:12876) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:12876) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
A list of missing libraries was provided. After successful installments, firefox ran fine. I upgraded again to version 1.10 and firefox still works.
Check out the latest blogs from LambdaTest on this topic:
The best agile teams are built from people who work together as one unit, where each team member has both the technical and the personal skills to allow the team to become self-organized, cross-functional, and self-motivated. These are all big words that I hear in almost every agile project. Still, the criteria to make a fantastic agile team are practically impossible to achieve without one major factor: motivation towards a common goal.
If you are a web tester then somewhere down the road you will have to come across Selenium, an open-source test automation framework that has been on boom ever since its launch in 2004.
Hey everyone! We hope you had a great Hacktober. At LambdaTest, we thrive to bring you the best with each update. Our engineering and tech teams work at lightning speed to deliver you a seamless testing experience.
Continuous integration is a coding philosophy and set of practices that encourage development teams to make small code changes and check them into a version control repository regularly. Most modern applications necessitate the development of code across multiple platforms and tools, so teams require a consistent mechanism for integrating and validating changes. Continuous integration creates an automated way for developers to build, package, and test their applications. A consistent integration process encourages developers to commit code changes more frequently, resulting in improved collaboration and code quality.
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!!