Best JavaScript code snippet using testcafe
exit-handler.js
Source:exit-handler.js
...83 // // easier so we dont need to t.plan() every test to84 // // make sure we get process.exit called85 exitHandler: (...args) => new Promise(resolve => {86 process.once('exit', resolve)87 exitHandler(...args)88 }),89 }90}91// Create errors with properties to be used in tests92const err = (message = '', options = {}, noStack = false) => {93 const e = Object.assign(94 new Error(message),95 typeof options !== 'object' ? { code: options } : options96 )97 e.stack = options.stack || `Error: ${message}`98 if (noStack) {99 delete e.stack100 }101 return e102}103t.test('handles unknown error with logs and debug file', async (t) => {104 const { exitHandler, debugFile, logs } = await mockExitHandler(t)105 await exitHandler(err('Unknown error', 'ECODE'))106 const debugContent = await debugFile()107 t.equal(process.exitCode, 1)108 logs.forEach((logItem, i) => {109 const logLines = format(i, ...logItem).trim().split(os.EOL)110 logLines.forEach((line) => {111 t.match(debugContent.trim(), line, 'log appears in debug file')112 })113 })114 const lastLog = debugContent115 .split('\n')116 .reduce((__, l) => parseInt(l.match(/^(\d+)\s/)[1]))117 t.equal(logs.length, lastLog + 1)118 t.match(logs.error, [119 ['code', 'ECODE'],120 ['ERR SUMMARY', 'Unknown error'],121 ['ERR DETAIL', 'Unknown error'],122 ])123 t.match(debugContent, /\d+ error code ECODE/)124 t.match(debugContent, /\d+ error ERR SUMMARY Unknown error/)125 t.match(debugContent, /\d+ error ERR DETAIL Unknown error/)126 t.matchSnapshot(logs, 'logs')127 t.matchSnapshot(debugContent, 'debug file contents')128})129t.test('exit handler never called - loglevel silent', async (t) => {130 const { logs, errors } = await mockExitHandler(t, {131 config: { loglevel: 'silent' },132 })133 process.emit('exit', 1)134 t.match(logs.error, [135 ['', /Exit handler never called/],136 ['', /error with npm itself/],137 ])138 t.strictSame(errors, [''], 'logs one empty string to console.error')139})140t.test('exit handler never called - loglevel notice', async (t) => {141 const { logs, errors } = await mockExitHandler(t)142 process.emit('exit', 1)143 t.equal(process.exitCode, 1)144 t.match(logs.error, [145 ['', /Exit handler never called/],146 ['', /error with npm itself/],147 ])148 t.strictSame(errors, ['', ''], 'logs two empty strings to console.error')149})150t.test('exit handler never called - no npm', async (t) => {151 const { logs, errors } = await mockExitHandler(t, { init: false })152 process.emit('exit', 1)153 t.equal(process.exitCode, 1)154 t.match(logs.error, [155 ['', /Exit handler never called/],156 ['', /error with npm itself/],157 ])158 t.strictSame(errors, [''], 'logs one empty string to console.error')159})160t.test('exit handler called - no npm', async (t) => {161 const { exitHandler, errors } = await mockExitHandler(t, { init: false })162 await exitHandler()163 t.equal(process.exitCode, 1)164 t.match(errors, [/Error: Exit prior to setting npm in exit handler/])165})166t.test('exit handler called - no npm with error', async (t) => {167 const { exitHandler, errors } = await mockExitHandler(t, { init: false })168 await exitHandler(err('something happened'))169 t.equal(process.exitCode, 1)170 t.match(errors, [/Error: something happened/])171})172t.test('exit handler called - no npm with error without stack', async (t) => {173 const { exitHandler, errors } = await mockExitHandler(t, { init: false })174 await exitHandler(err('something happened', {}, true))175 t.equal(process.exitCode, 1)176 t.match(errors, [/something happened/])177})178t.test('console.log output using --json', async (t) => {179 const { exitHandler, errors } = await mockExitHandler(t, {180 config: {181 json: true,182 },183 })184 await exitHandler(err('Error: EBADTHING Something happened'))185 t.equal(process.exitCode, 1)186 t.same(187 JSON.parse(errors[0]),188 {189 error: {190 code: 'EBADTHING', // should default error code to E[A-Z]+191 summary: 'Error: EBADTHING Something happened',192 detail: 'Error: EBADTHING Something happened',193 },194 },195 'should output expected json output'196 )197})198t.test('throw a non-error obj', async (t) => {199 const { exitHandler, logs } = await mockExitHandler(t)200 await exitHandler({201 code: 'ESOMETHING',202 message: 'foo bar',203 })204 t.equal(process.exitCode, 1)205 t.match(logs.error, [206 ['weird error', { code: 'ESOMETHING', message: 'foo bar' }],207 ])208})209t.test('throw a string error', async (t) => {210 const { exitHandler, logs } = await mockExitHandler(t)211 await exitHandler('foo bar')212 t.equal(process.exitCode, 1)213 t.match(logs.error, [214 ['', 'foo bar'],215 ])216})217t.test('update notification', async (t) => {218 const { exitHandler, logs, npm } = await mockExitHandler(t)219 npm.updateNotification = 'you should update npm!'220 await exitHandler()221 t.match(logs.notice, [222 ['', 'you should update npm!'],223 ])224})225t.test('npm.config not ready', async (t) => {226 const { exitHandler, logs, errors } = await mockExitHandler(t, {227 load: false,228 })229 await exitHandler()230 t.equal(process.exitCode, 1)231 t.match(errors, [232 /Error: Exit prior to config file resolving./,233 ], 'should exit with config error msg')234 t.match(logs.verbose, [235 ['stack', /Error: Exit prior to config file resolving./],236 ], 'should exit with config error msg')237})238t.test('timing with no error', async (t) => {239 const { exitHandler, timingFile, npm, logs } = await mockExitHandler(t, {240 config: {241 timing: true,242 },243 })244 await exitHandler()245 const timingFileData = await timingFile()246 t.equal(process.exitCode, 0)247 t.match(logs.error, [248 ['', /A complete log of this run can be found in:[\s\S]*-debug-\d\.log/],249 ])250 t.match(251 timingFileData,252 Object.keys(npm.finishedTimers).reduce((acc, k) => {253 acc[k] = Number254 return acc255 }, {})256 )257 t.strictSame(npm.unfinishedTimers, new Map())258 t.match(timingFileData, {259 command: [],260 version: '1.0.0',261 npm: Number,262 logfile: String,263 logfiles: [String],264 })265})266t.test('unfinished timers', async (t) => {267 const { exitHandler, timingFile, npm } = await mockExitHandler(t, {268 config: {269 timing: true,270 },271 })272 process.emit('time', 'foo')273 process.emit('time', 'bar')274 await exitHandler()275 const timingFileData = await timingFile()276 t.equal(process.exitCode, 0)277 t.match(npm.unfinishedTimers, new Map([['foo', Number], ['bar', Number]]))278 t.match(timingFileData, {279 command: [],280 version: '1.0.0',281 npm: Number,282 logfile: String,283 logfiles: [String],284 unfinished: {285 foo: [Number, Number],286 bar: [Number, Number],287 },288 })289})290t.test('uses code from errno', async (t) => {291 const { exitHandler, logs } = await mockExitHandler(t)292 await exitHandler(err('Error with errno', { errno: 127 }))293 t.equal(process.exitCode, 127)294 t.match(logs.error, [['errno', 127]])295})296t.test('uses code from number', async (t) => {297 const { exitHandler, logs } = await mockExitHandler(t)298 await exitHandler(err('Error with code type number', 404))299 t.equal(process.exitCode, 404)300 t.match(logs.error, [['code', 404]])301})302t.test('uses all err special properties', async t => {303 const { exitHandler, logs } = await mockExitHandler(t)304 const keys = ['code', 'syscall', 'file', 'path', 'dest', 'errno']305 const properties = keys.reduce((acc, k) => {306 acc[k] = `${k}-hey`307 return acc308 }, {})309 await exitHandler(err('Error with code type number', properties))310 t.equal(process.exitCode, 1)311 t.match(logs.error, keys.map((k) => [k, `${k}-hey`]), 'all special keys get logged')312})313t.test('verbose logs replace info on err props', async t => {314 const { exitHandler, logs } = await mockExitHandler(t)315 const keys = ['type', 'stack', 'statusCode', 'pkgid']316 const properties = keys.reduce((acc, k) => {317 acc[k] = `${k}-https://user:pass@registry.npmjs.org/`318 return acc319 }, {})320 await exitHandler(err('Error with code type number', properties))321 t.equal(process.exitCode, 1)322 t.match(323 logs.verbose.filter(([p]) => p !== 'logfile'),324 keys.map((k) => [k, `${k}-https://user:***@registry.npmjs.org/`]),325 'all special keys get replaced'326 )327})328t.test('call exitHandler with no error', async (t) => {329 const { exitHandler, logs } = await mockExitHandler(t)330 await exitHandler()331 t.equal(process.exitCode, 0)332 t.match(logs.error, [])333})334t.test('defaults to log error msg if stack is missing when unloaded', async (t) => {335 const { exitHandler, logs, errors } = await mockExitHandler(t, { load: false })336 await exitHandler(err('Error with no stack', { code: 'ENOSTACK', errno: 127 }, true))337 t.equal(process.exitCode, 127)338 t.same(errors, ['Error with no stack'], 'should use error msg')339 t.match(logs.error, [340 ['code', 'ENOSTACK'],341 ['errno', 127],342 ])343})344t.test('exits uncleanly when only emitting exit event', async (t) => {345 const { logs } = await mockExitHandler(t)346 process.emit('exit')347 t.match(logs.error, [['', 'Exit handler never called!']])348 t.equal(process.exitCode, 1, 'exitCode coerced to 1')349 t.end()350})351t.test('do no fancy handling for shellouts', async t => {352 const { exitHandler, npm, logs } = await mockExitHandler(t)353 npm.command = 'exec'354 const loudNoises = () =>355 logs.filter(([level]) => ['warn', 'error'].includes(level))356 t.test('shellout with a numeric error code', async t => {357 await exitHandler(err('', 5))358 t.equal(process.exitCode, 5, 'got expected exit code')359 t.strictSame(loudNoises(), [], 'no noisy warnings')360 })361 t.test('shellout without a numeric error code (something in npm)', async t => {362 await exitHandler(err('', 'banana stand'))363 t.equal(process.exitCode, 1, 'got expected exit code')364 // should log some warnings and errors, because something weird happened365 t.strictNotSame(loudNoises(), [], 'bring the noise')366 t.end()367 })368 t.test('shellout with code=0 (extra weird?)', async t => {369 await exitHandler(Object.assign(new Error(), { code: 0 }))370 t.equal(process.exitCode, 1, 'got expected exit code')371 t.strictNotSame(loudNoises(), [], 'bring the noise')372 })373 t.end()...
cli.js
Source:cli.js
...36 try {37 await npm.load()38 if (npm.config.get('version', 'cli')) {39 npm.output(npm.version)40 return exitHandler()41 }42 // npm --versions=cli43 if (npm.config.get('versions', 'cli')) {44 npm.argv = ['version']45 npm.config.set('usage', false, 'cli')46 }47 updateNotifier(npm)48 cmd = npm.argv.shift()49 if (!cmd) {50 npm.output(await npm.usage)51 process.exitCode = 152 return exitHandler()53 }54 await npm.exec(cmd, npm.argv)55 return exitHandler()56 } catch (err) {57 if (err.code === 'EUNKNOWNCOMMAND') {58 const didYouMean = require('./utils/did-you-mean.js')59 const suggestions = await didYouMean(npm, npm.localPrefix, cmd)60 npm.output(`Unknown command: "${cmd}"${suggestions}\n`)61 npm.output('To see a list of supported npm commands, run:\n npm help')62 process.exitCode = 163 return exitHandler()64 }65 return exitHandler(err)66 }...
index.js
Source:index.js
1/*2#!/usr/bin/env node3process.stdin.resume();4let hasClosed = false;5function exitHandler() {6 if (!hasClosed) {7 hasClosed = true;8 console.log("Shutting down...");9 process.exit();10 }11}12// do something when app is closing13process.on('exit', exitHandler.bind(null));14// catches ctrl+c event15process.on('SIGINT', exitHandler.bind(null));16// catches "kill pid"17process.on('SIGUSR1', exitHandler.bind(null));18process.on('SIGUSR2', exitHandler.bind(null));19process.on('SIGTERM', exitHandler.bind(null));...
error.js
Source:error.js
...16}17// This closes the server in the event of an error so18// that our requests do not hang19function setupCloseOnExit(server) {20 async function exitHandler(options = {}) {21 await server22 .close()23 .then(() => {24 logger.info("Server successfully closed");25 })26 .catch((error) => {27 logger.warn("Something went wrong closing the server", error.stack);28 });29 if (options.exit) process.exit();30 }31 // Do something when app is closing32 process.on("exit", exitHandler);33 // Catches ctrl+c event34 process.on("SIGINT", exitHandler.bind(null, { exit: true }));...
main.js
Source:main.js
...14process.on('SIGUSR1', exitHandler.bind(null, { exit: true }));15process.on('SIGUSR2', exitHandler.bind(null, { exit: true }));16// catches uncaught exceptions17process.on('uncaughtException', exitHandler.bind(null, { exit: true }));18async function exitHandler(options, exitCode) {19 // await app.disconnect()20 if (options.cleanup) {21 await app.disconnect()22 console.log('\nprograma finalizado normalmente')23 }24 if (exitCode || exitCode === 0) {25 console.log(`\nprograma finalizado con codigo: ${exitCode}`)26 }27 if (options.exit) {28 process.exit()29 }30}31/////////////////////////////////////////////////////////////////32app.setOnReady(async (port) => {...
app.js
Source:app.js
...14 } catch (err) {15 console.error('ERROR: Booting error', err.message || err);16 }17})();18function exitHandler(error) {19 if (error) console.error(error);20 console.log('Gracefully stopping...');21 clearInterval(intervalID);22 server.close(async (err) => {23 if (err) {24 console.error(err, 'ERROR: Failed to close server!');25 } else {26 console.log('INFO: Server has been stopped.');27 }28 await db.end();29 process.exit(1);30 });31}32// Catches ctrl+c event...
webserver.js
Source:webserver.js
1#!/usr/bin/env node2//process.stdin.resume();3//let hasClosed = false;4//function exitHandler() {5// if (!hasClosed) {6// hasClosed = true;7// console.log("Shutting down...");8//9// process.exit();10// }11//}12// do something when app is closing13//process.on('exit', exitHandler.bind(null));14// catches ctrl+c event15//process.on('SIGINT', exitHandler.bind(null));16// catches "kill pid"17//process.on('SIGUSR1', exitHandler.bind(null));18//process.on('SIGUSR2', exitHandler.bind(null));...
setupCloseOnExit.js
Source:setupCloseOnExit.js
1const setupCloseOnExit = server => {2 const exitHandler = async signal => {3 try {4 await server.close()5 console.info(`Got ${signal}. Graceful shutdown. Server successfully closed.`)6 process.exit()7 } catch (error) {8 console.warn('Something went wrong closing the server.', error.stack)9 process.exitCode = 110 }11 }12 process.on('exit', exitHandler)13 process.on('SIGINT', exitHandler)14 process.on('SIGHUP', exitHandler)15 process.on('uncaughtException', exitHandler)16 process.on('unhandledRejection', exitHandler)17}...
Using AI Code Generation
1import { Selector } from 'testcafe';2test('My first test', async t => {3 .typeText('#developer-name', 'John Smith')4 .click('#submit-button')5 .expect(Selector('#article-header').innerText).eql('Thank you, John Smith!');6});7import { exitHandler } from 'testcafe';8test('My first test', async t => {9 .typeText('#developer-name', 'John Smith')10 .click('#submit-button')11 .expect(Selector('#article-header').innerText).eql('Thank you, John Smith!');12}).after(exitHandler);13test('My first test', async t => {14 .typeText('#developer-name', 'John Smith')15 .click('#submit-button')16 .expect(Selector('#article-header').innerText).eql('Thank you, John Smith!');17}).after(async t => {18 await t.takeScreenshot();19});20test('My first test', async t => {21 .typeText('#developer-name', 'John Smith')22 .click('#submit-button')
Using AI Code Generation
1import { Selector } from 'testcafe';2test('My test', async t => {3 const developerNameInput = Selector('#developer-name');4 .typeText(developerNameInput, 'Peter')5 .click('#submit-button');6});7import { exitHandler } from './testcafe-utils.js';8 .before(exitHandler)9 .after(exitHandler)10 ('My test', async t => {11 const developerNameInput = Selector('#developer-name');12 .typeText(developerNameInput, 'Peter')13 .click('#submit-button');14 });15import { exitHandler } from './testcafe-utils.js';16 .before(exitHandler)17 .after(exitHandler)18 ('My test', async t => {19 const developerNameInput = Selector('#developer-name');20 .typeText(developerNameInput, 'Peter')21 .click('#submit-button');22 });23import { exitHandler } from './testcafe-utils.js';24 .before(exitHandler)25 .after(exitHandler)26 ('My test', async t => {27 const developerNameInput = Selector('#developer-name');28 .typeText(developerNameInput, 'Peter')29 .click('#submit-button');30 });31import { exitHandler } from './testcafe-utils.js';32 .before(exitHandler)33 .after(exitHandler)34 ('My test', async t => {35 const developerNameInput = Selector('#developer-name');36 .typeText(developerNameInput, 'Peter')37 .click('#submit-button');38 });
Using AI Code Generation
1const TestcafeRunner = require('testcafe-runner');2const testcafeRunner = new TestcafeRunner();3testcafeRunner.exitHandler();4exitHandler() {5 .then(browsers => browsers.forEach(browser => browser.close()));6}7const TestcafeRunner = require('testcafe-runner');8const testcafeRunner = new TestcafeRunner();9testcafeRunner.exitHandler();10exitHandler() {11 .then(browsers => browsers.forEach(browser => browser.close()));12}13const TestcafeRunner = require('testcafe-runner');14const testcafeRunner = new TestcafeRunner();15testcafeRunner.exitHandler();16exitHandler() {17 .then(browsers => browsers.forEach(browser => browser.close()));18}19const TestcafeRunner = require('test
Using AI Code Generation
1import { Selector } from 'testcafe';2import { exitHandler } from './exitHandler';3 .afterEach(exitHandler);4test('My first test', async t => {5 .typeText('#developer-name', 'John Smith')6 .click('#submit-button');7});8import { Selector } from 'testcafe';9export async function exitHandler(t) {10 if (t.testRun.errs.length > 0) {11 await t.takeScreenshot();12 }13}
Using AI Code Generation
1 .afterEach(async t => {2 await t.wait(5000);3 })4 .after(async t => {5 await t.wait(5000);6 });7test('Exit handler', async t => {8 .typeText('#developer-name', 'John Smith')9 .click('#windows')10 .click('#submit-button');11});12process.on('exit', exitHandler.bind(null, {cleanup:true}));13process.on('exit', exitHandler.bind(null,{cleanup:true}));14process.on('SIGINT', exitHandler.bind(null, {exit:true}));15process.on('SIGUSR1', exitHandler.bind(null, {exit:true}));16process.on('SIGUSR2', exitHandler.bind(null, {exit:true}));17process.on('uncaughtException', exitHandler.bind(null, {exit:true}));18function exitHandler(options, err) {19 if (options.cleanup) {20 console.log('clean');21 }22 if (err) {23 console.log(err.stack);24 }25 if (options.exit) {26 process.exit();27 }28}
Using AI Code Generation
1const TestcafeHelper = require('./TestcafeHelper');2const testCafeHelper = new TestcafeHelper();3testCafeHelper.exitHandler();4const TestcafeHelper = require('./TestcafeHelper');5const testCafeHelper = new TestcafeHelper();6testCafeHelper.getTestcafeRunner();7const TestcafeHelper = require('./TestcafeHelper');8const testCafeHelper = new TestcafeHelper();9testCafeHelper.createTestCafe();10const TestcafeHelper = require('./TestcafeHelper');11const testCafeHelper = new TestcafeHelper();12testCafeHelper.getTestcafeInstance();13const TestcafeHelper = require('./TestcafeHelper');14const testCafeHelper = new TestcafeHelper();15testCafeHelper.getTestcafeRunner();16const TestcafeHelper = require('./TestcafeHelper');17const testCafeHelper = new TestcafeHelper();18testCafeHelper.getBrowserList();19const TestcafeHelper = require('./TestcafeHelper');20const testCafeHelper = new TestcafeHelper();21testCafeHelper.getBrowserList();22const TestcafeHelper = require('./TestcafeHelper');23const testCafeHelper = new TestcafeHelper();24testCafeHelper.getBrowserList();25const TestcafeHelper = require('./TestcafeHelper');26const testCafeHelper = new TestcafeHelper();27testCafeHelper.getBrowserList();28const TestcafeHelper = require('./TestcafeHelper');29const testCafeHelper = new TestcafeHelper();30testCafeHelper.getBrowserList();31const TestcafeHelper = require('./TestcafeHelper');
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!