Best JavaScript code snippet using best
index.js
Source:index.js
1/**2 * Copyright (c) 2014, Facebook, Inc. All rights reserved.3 *4 * This source code is licensed under the BSD-style license found in the5 * LICENSE file in the root directory of this source tree. An additional grant6 * of patent rights can be found in the PATENTS file in the same directory.7 *8 * @flow9 */10import type {AggregatedResult} from 'types/TestResult';11import type {Argv} from 'types/Argv';12import type {GlobalConfig, Path, ProjectConfig} from 'types/Config';13import {14 Console,15 clearLine,16 createDirectory,17 validateCLIOptions,18} from 'jest-util';19import {readConfig} from 'jest-config';20import {version as VERSION} from '../../package.json';21import args from './args';22import chalk from 'chalk';23import createContext from '../lib/create_context';24import getChangedFilesPromise from '../get_changed_files_promise';25import getJest from './get_jest';26import handleDeprecationWarnings from '../lib/handle_deprecation_warnings';27import logDebugMessages from '../lib/log_debug_messages';28import preRunMessage from '../pre_run_message';29import runJest from '../run_jest';30import Runtime from 'jest-runtime';31import TestWatcher from '../test_watcher';32import watch from '../watch';33import yargs from 'yargs';34async function run(maybeArgv?: Argv, project?: Path) {35 const argv: Argv = _buildArgv(maybeArgv, project);36 const projects = _getProjectListFromCLIArgs(argv, project);37 // If we're running a single Jest project, we might want to use another38 // version of Jest (the one that is specified in this project's package.json)39 const runCLIFn = _getRunCLIFn(projects);40 const {results, globalConfig} = await runCLIFn(argv, projects);41 _readResultsAndExit(results, globalConfig);42}43const runCLI = async (44 argv: Argv,45 projects: Array<Path>,46): Promise<{results: AggregatedResult, globalConfig: GlobalConfig}> => {47 let results;48 // Optimize 'fs' module and make it more compatible with multiple platforms.49 _patchGlobalFSModule();50 // If we output a JSON object, we can't write anything to stdout, since51 // it'll break the JSON structure and it won't be valid.52 const outputStream =53 argv.json || argv.useStderr ? process.stderr : process.stdout;54 argv.version && _printVersionAndExit(outputStream);55 try {56 const {globalConfig, configs, hasDeprecationWarnings} = _getConfigs(57 projects,58 argv,59 outputStream,60 );61 await _run(62 globalConfig,63 configs,64 hasDeprecationWarnings,65 outputStream,66 (r: AggregatedResult) => (results = r),67 );68 if (argv.watch || argv.watchAll) {69 // If in watch mode, return the promise that will never resolve.70 // If the watch mode is interrupted, watch should handle the process71 // shutdown.72 return new Promise(() => {});73 }74 if (!results) {75 throw new Error(76 'AggregatedResult must be present after test run is complete',77 );78 }79 return Promise.resolve({globalConfig, results});80 } catch (error) {81 clearLine(process.stderr);82 clearLine(process.stdout);83 console.error(chalk.red(error.stack));84 process.exit(1);85 throw error;86 }87};88const _readResultsAndExit = (89 result: ?AggregatedResult,90 globalConfig: GlobalConfig,91) => {92 const code = !result || result.success ? 0 : globalConfig.testFailureExitCode;93 process.on('exit', () => process.exit(code));94 if (globalConfig.forceExit) {95 process.exit(code);96 }97};98const _buildArgv = (maybeArgv: ?Argv, project: ?Path) => {99 const argv: Argv = yargs(maybeArgv || process.argv.slice(2))100 .usage(args.usage)101 .help()102 .alias('help', 'h')103 .options(args.options)104 .epilogue(args.docs)105 .check(args.check).argv;106 validateCLIOptions(argv, args.options);107 return argv;108};109const _getProjectListFromCLIArgs = (argv, project: ?Path) => {110 const projects = argv.projects ? argv.projects : [];111 if (project) {112 projects.push(project);113 }114 if (!projects.length) {115 projects.push(process.cwd());116 }117 return projects;118};119const _getRunCLIFn = (projects: Array<Path>) =>120 projects.length === 1 ? getJest(projects[0]).runCLI : runCLI;121const _printDebugInfoAndExitIfNeeded = (122 argv,123 globalConfig,124 configs,125 outputStream,126) => {127 if (argv.debug || argv.showConfig) {128 logDebugMessages(globalConfig, configs, outputStream);129 }130 if (argv.showConfig) {131 process.exit(0);132 }133};134const _printVersionAndExit = outputStream => {135 outputStream.write(`v${VERSION}\n`);136 process.exit(0);137};138const _ensureNoDuplicateConfigs = (parsedConfigs, projects) => {139 const configPathSet = new Set();140 for (const {configPath} of parsedConfigs) {141 if (configPathSet.has(configPath)) {142 let message =143 'One or more specified projects share the same config file\n';144 parsedConfigs.forEach(({configPath}, index) => {145 message =146 message +147 '\nProject: "' +148 projects[index] +149 '"\nConfig: "' +150 String(configPath) +151 '"';152 });153 throw new Error(message);154 }155 configPathSet.add(configPath);156 }157};158// Possible scenarios:159// 1. jest --config config.json160// 2. jest --projects p1 p2161// 3. jest --projects p1 p2 --config config.json162// 4. jest --projects p1163// 5. jest164//165// If no projects are specified, process.cwd() will be used as the default166// (and only) project.167const _getConfigs = (168 projectsFromCLIArgs: Array<Path>,169 argv: Argv,170 outputStream,171): {172 globalConfig: GlobalConfig,173 configs: Array<ProjectConfig>,174 hasDeprecationWarnings: boolean,175} => {176 let globalConfig;177 let hasDeprecationWarnings;178 let configs: Array<ProjectConfig> = [];179 let projects = projectsFromCLIArgs;180 if (projectsFromCLIArgs.length === 1) {181 const parsedConfig = readConfig(argv, projects[0]);182 if (parsedConfig.globalConfig.projects) {183 // If this was a single project, and its config has `projects`184 // settings, use that value instead.185 projects = parsedConfig.globalConfig.projects;186 }187 hasDeprecationWarnings = parsedConfig.hasDeprecationWarnings;188 globalConfig = parsedConfig.globalConfig;189 configs = [parsedConfig.projectConfig];190 if (globalConfig.projects && globalConfig.projects.length) {191 // Even though we had one project in CLI args, there might be more192 // projects defined in the config.193 projects = globalConfig.projects;194 }195 }196 if (projects.length > 1) {197 const parsedConfigs = projects.map(root => readConfig(argv, root, true));198 _ensureNoDuplicateConfigs(parsedConfigs, projects);199 configs = parsedConfigs.map(({projectConfig}) => projectConfig);200 if (!hasDeprecationWarnings) {201 hasDeprecationWarnings = parsedConfigs.some(202 ({hasDeprecationWarnings}) => !!hasDeprecationWarnings,203 );204 }205 // If no config was passed initially, use the one from the first project206 if (!globalConfig) {207 globalConfig = parsedConfigs[0].globalConfig;208 }209 }210 if (!globalConfig || !configs.length) {211 throw new Error('jest: No configuration found for any project.');212 }213 _printDebugInfoAndExitIfNeeded(argv, globalConfig, configs, outputStream);214 return {215 configs,216 globalConfig,217 hasDeprecationWarnings: !!hasDeprecationWarnings,218 };219};220const _patchGlobalFSModule = () => {221 const realFs = require('fs');222 const fs = require('graceful-fs');223 fs.gracefulify(realFs);224};225const _buildContextsAndHasteMaps = async (226 configs,227 globalConfig,228 outputStream,229) => {230 const hasteMapInstances = Array(configs.length);231 const contexts = await Promise.all(232 configs.map(async (config, index) => {233 createDirectory(config.cacheDirectory);234 const hasteMapInstance = Runtime.createHasteMap(config, {235 console: new Console(outputStream, outputStream),236 maxWorkers: globalConfig.maxWorkers,237 resetCache: !config.cache,238 watch: globalConfig.watch,239 watchman: globalConfig.watchman,240 });241 hasteMapInstances[index] = hasteMapInstance;242 return createContext(config, await hasteMapInstance.build());243 }),244 );245 return {contexts, hasteMapInstances};246};247const _run = async (248 globalConfig,249 configs,250 hasDeprecationWarnings,251 outputStream,252 onComplete,253) => {254 // Queries to hg/git can take a while, so we need to start the process255 // as soon as possible, so by the time we need the result it's already there.256 const changedFilesPromise = getChangedFilesPromise(globalConfig, configs);257 const {contexts, hasteMapInstances} = await _buildContextsAndHasteMaps(258 configs,259 globalConfig,260 outputStream,261 );262 globalConfig.watch || globalConfig.watchAll263 ? await _runWatch(264 contexts,265 configs,266 hasDeprecationWarnings,267 globalConfig,268 outputStream,269 hasteMapInstances,270 changedFilesPromise,271 )272 : await _runWithoutWatch(273 globalConfig,274 contexts,275 outputStream,276 onComplete,277 changedFilesPromise,278 );279};280const _runWatch = async (281 contexts,282 configs,283 hasDeprecationWarnings,284 globalConfig,285 outputStream,286 hasteMapInstances,287 changedFilesPromise,288) => {289 if (hasDeprecationWarnings) {290 try {291 await handleDeprecationWarnings(outputStream, process.stdin);292 return watch(globalConfig, contexts, outputStream, hasteMapInstances);293 } catch (e) {294 process.exit(0);295 }296 }297 return watch(globalConfig, contexts, outputStream, hasteMapInstances);298};299const _runWithoutWatch = async (300 globalConfig,301 contexts,302 outputStream,303 onComplete,304 changedFilesPromise,305) => {306 const startRun = async () => {307 if (!globalConfig.listTests) {308 preRunMessage.print(outputStream);309 }310 return await runJest({311 changedFilesPromise,312 contexts,313 globalConfig,314 onComplete,315 outputStream,316 startRun,317 testWatcher: new TestWatcher({isWatchMode: false}),318 });319 };320 return await startRun();321};322module.exports = {323 run,324 runCLI,...
resolve-config.ts
Source:resolve-config.ts
1/*2 * Copyright (c) 2019, salesforce.com, inc.3 * All rights reserved.4 * SPDX-License-Identifier: MIT5 * For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/MIT6*/7import fs from 'fs';8import path from 'path';9import { PACKAGE_JSON, BEST_CONFIG } from './constants';10import { UserConfig } from '@best/types';11function isFile(filePath:string) {12 return fs.existsSync(filePath) && !fs.lstatSync(filePath).isDirectory();13}14export function resolveConfigPathByTraversing(pathToResolve: string, initialPath: string, cwd: string): string {15 const bestConfig = path.resolve(pathToResolve, BEST_CONFIG);16 if (isFile(bestConfig)) {17 return bestConfig;18 }19 const packageJson = path.resolve(pathToResolve, PACKAGE_JSON);20 if (isFile(packageJson)) {21 return packageJson;22 }23 if (pathToResolve === path.dirname(pathToResolve)) {24 throw new Error(`No config found in ${initialPath}`);25 }26 // go up a level and try it again27 return resolveConfigPathByTraversing(path.dirname(pathToResolve), initialPath, cwd);28}29export function resolveConfigPath(pathToResolve: string, cwd: string) {30 const absolutePath = path.isAbsolute(pathToResolve) ? pathToResolve : path.resolve(cwd, pathToResolve);31 if (isFile(absolutePath)) {32 return absolutePath;33 }34 return resolveConfigPathByTraversing(absolutePath, pathToResolve, cwd);35}36export function readConfigAndSetRootDir(configPath: string): UserConfig {37 const isJSON = configPath.endsWith('.json');38 let configObject;39 try {40 configObject = require(configPath);41 } catch (error) {42 if (isJSON) {43 throw new Error(`Best: Failed to parse config file ${configPath}\n`);44 } else {45 throw error;46 }47 }48 if (configPath.endsWith(PACKAGE_JSON)) {49 if (!configObject.best) {50 throw new Error(`No "best" section has been found in ${configPath}`);51 }52 configObject = configObject.best;53 }54 if (!configObject) {55 throw new Error("Couldn't find any configuration for Best.");56 }57 if (configObject.rootDir) {58 // We don't touch it if it has an absolute path specified59 if (!path.isAbsolute(configObject.rootDir)) {60 // otherwise, we'll resolve it relative to the file's __dirname61 configObject.rootDir = path.resolve(path.dirname(configPath), configObject.rootDir);62 }63 } else {64 // If rootDir is not there, we'll set it to this file's __dirname65 configObject.rootDir = path.dirname(configPath);66 }67 if (!configObject.projectName) {68 throw new Error('A best project must have a projectName');69 }70 return configObject;71}72export function ensureNoDuplicateConfigs(parsedConfigs: any, projects: string[]) {73 const configPathSet = new Set();74 for (const { configPath } of parsedConfigs) {75 if (configPathSet.has(configPath)) {76 let message = 'One or more specified projects share the same config file\n';77 parsedConfigs.forEach((projectConfig: any, index: number) => {78 message =79 message +80 '\nProject: "' +81 projects[index] +82 '"\nConfig: "' +83 String(projectConfig.configPath) +84 '"';85 });86 throw new Error(message);87 }88 if (configPath !== null) {89 configPathSet.add(configPath);90 }91 }...
lint-ts.ts
Source:lint-ts.ts
1import * as ChildProcess from 'child_process';2import * as FS from 'fs';3import * as Path from 'path';4import 'villa/platform/node';5import stripJsonComments from 'strip-json-comments';6import * as v from 'villa';7const CONCURRENCY = Number(process.env.LINT_TS_PROJECTS_CONCURRENCY) || 4;8const [, , pattern] = process.argv;9const cwd = process.cwd();10const entranceConfigPath = normalize(cwd, 'tsconfig.json');11let configPathSet = new Set<string>();12resolve(entranceConfigPath);13let configPaths = Array.from(configPathSet);14if (pattern) {15 console.info(`Filtering with pattern "${pattern}"...`);16 configPaths = configPaths.filter(configPath => configPath.includes(pattern));17}18let havingError = false;19v.parallel(20 configPaths,21 async configPath => {22 let relativeProjectPath = Path.dirname(Path.relative(cwd, configPath));23 console.info(`Linting "${relativeProjectPath}"...`);24 let cp = ChildProcess.spawn('node', [25 'node_modules/tslint/bin/tslint',26 '--project',27 configPath,28 '--format',29 'verbose',30 ]);31 cp.stdout.pipe(process.stdout);32 cp.stderr.pipe(process.stderr);33 try {34 await v.awaitable(cp);35 console.info(`Done linting "${relativeProjectPath}".`);36 } catch (error) {37 havingError = true;38 }39 },40 CONCURRENCY,41)42 .then(() => {43 process.exit(havingError ? 1 : 0);44 })45 .catch(error => {46 console.error(error);47 process.exit(1);48 });49function resolve(configPath: string): void {50 let jsonc = FS.readFileSync(configPath, 'utf8');51 interface Reference {52 path: string;53 }54 let references = JSON.parse(stripJsonComments(jsonc)).references as55 | Reference[]56 | undefined;57 if (!references) {58 return;59 }60 let configDirName = Path.dirname(configPath);61 let dependencies = references.map(reference =>62 normalize(Path.resolve(configDirName, reference.path)),63 );64 for (let dependencyConfigPath of dependencies) {65 configPathSet.add(dependencyConfigPath);66 resolve(dependencyConfigPath);67 }68}69function normalize(70 configPath: string,71 configFileName = 'tsconfig.json',72): string {73 let stat = FS.statSync(configPath);74 if (!stat) {75 throw new Error(`Invalid config path: "${configPath}"`);76 }77 if (stat.isDirectory()) {78 return Path.join(configPath, configFileName);79 } else {80 return configPath;81 }...
Using AI Code Generation
1var bestFitModule = require('BestFit');2var configPathSet = bestFitModule.configPathSet;3configPathSet('test1.js', 'test2.js', 'test3.js');4var bestFitModule = require('BestFit');5var configPathSet = bestFitModule.configPathSet;6configPathSet('test1.js', 'test2.js', 'test3.js', 'test4.js');7var bestFitModule = require('BestFit');8var configPathSet = bestFitModule.configPathSet;9configPathSet('test1.js', 'test2.js', 'test3.js', 'test4.js', 'test5.js');10var bestFitModule = require('BestFit');11var configPathSet = bestFitModule.configPathSet;12configPathSet('test1.js', 'test2.js', 'test3.js', 'test4.js', 'test5.js', 'test6.js');13var bestFitModule = require('BestFit');14var configPathSet = bestFitModule.configPathSet;15configPathSet('test1.js', 'test2.js', 'test3.js', 'test4.js', 'test5.js', 'test6.js', 'test7.js');16var bestFitModule = require('BestFit');17var configPathSet = bestFitModule.configPathSet;18configPathSet('test1.js', 'test2.js', 'test3.js', 'test4.js', 'test5.js', 'test6.js', 'test7.js', 'test8.js');19var bestFitModule = require('BestFit');20var configPathSet = bestFitModule.configPathSet;21configPathSet('test1.js', 'test2.js', 'test3.js', 'test4.js', 'test5.js', 'test6.js', 'test7.js', '
Using AI Code Generation
1var configPathSet = require('./BestPractice.js');2configPathSet.configPathSet('./config.json');3var BestPractice = require('./BestPractice.js');4var bp = new BestPractice();5bp.getBestPractice('test1', function(err, result){6 if(err){7 console.log(err);8 }else{9 console.log(result);10 }11});12bp.getBestPractice('test2', function(err, result){13 if(err){14 console.log(err);15 }else{16 console.log(result);17 }18});19bp.getBestPractice('test3', function(err, result){20 if(err){21 console.log(err);22 }else{23 console.log(result);24 }25});26bp.getBestPractice('test4', function(err, result){27 if(err){28 console.log(err);29 }else{30 console.log(result);31 }32});33bp.getBestPractice('test5', function(err, result){34 if(err){35 console.log(err);36 }else{37 console.log(result);38 }39});40bp.getBestPractice('test6', function(err, result){41 if(err){42 console.log(err);43 }else{44 console.log(result);45 }46});47bp.getBestPractice('test7', function(err, result){48 if(err){49 console.log(err);50 }else{51 console.log(result);52 }53});54bp.getBestPractice('test8', function(err, result){55 if(err){56 console.log(err);57 }else{58 console.log(result);59 }60});61bp.getBestPractice('test9', function(err, result){62 if(err){63 console.log(err);64 }else{65 console.log(result);66 }67});
Using AI Code Generation
1var BestPractice = require('bestpractice');2var bestPractice = new BestPractice();3bestPractice.configPathSet('/home/username/bestpractice/config.json');4var configPath = bestPractice.configPathGet();5console.log('The path for configuration file is: ' + configPath);6var BestPractice = require('bestpractice');7var bestPractice = new BestPractice();8bestPractice.configPathSet('/home/username/bestpractice/config.json');9var configPath = bestPractice.configPathGet();10console.log('The path for configuration file is: ' + configPath);11var BestPractice = require('bestpractice');12var bestPractice = new BestPractice();13bestPractice.configPathSet('/home/username/bestpractice/config.json');14var configPath = bestPractice.configPathGet();15console.log('The path for configuration file is: ' + configPath);16var BestPractice = require('bestpractice');17var bestPractice = new BestPractice();18bestPractice.configPathSet('/home/username/bestpractice/config.json');
Using AI Code Generation
1var BestPracticeConfig = require('./bestpracticeconfig');2var config = new BestPracticeConfig();3config.configPathSet('test4.js');4console.log('config.path: '+config.path);5var BestPracticeConfig = require('./bestpracticeconfig');6var config = new BestPracticeConfig();7config.configPathSet('test5.js');8console.log('config.path: '+config.path);9var BestPracticeConfig = require('./bestpracticeconfig');10var config = new BestPracticeConfig();11config.configPathSet('test6.js');12console.log('config.path: '+config.path);13var BestPracticeConfig = require('./bestpracticeconfig');14var config = new BestPracticeConfig();15config.configPathSet('test7.js');16console.log('config.path: '+config.path);17var BestPracticeConfig = require('./bestpracticeconfig');18var config = new BestPracticeConfig();19config.configPathSet('test8.js');20console.log('config.path: '+config.path);21var BestPracticeConfig = require('./bestpracticeconfig');22var config = new BestPracticeConfig();23config.configPathSet('test9.js');24console.log('config.path: '+config.path);25var BestPracticeConfig = require('./bestpracticeconfig');26var config = new BestPracticeConfig();27config.configPathSet('test10.js');28console.log('config.path: '+config.path);29var BestPracticeConfig = require('./bestpracticeconfig');30var config = new BestPracticeConfig();31config.configPathSet('test11.js');32console.log('config.path: '+config.path);33var BestPracticeConfig = require('./bestpracticeconfig');34var config = new BestPracticeConfig();
Using AI Code Generation
1BestPractice.configPathSet('config.json');2console.log(BestPractice.configPathGet());3BestPractice.set('key1', 'value1');4console.log(BestPractice.get('key1'));5BestPractice.set('key1', 'value1');6console.log(BestPractice.get('key1'));7BestPractice.set('key1', 'value1');8console.log(BestPractice.get('key1'));9BestPractice.set('key1', 'value1');10console.log(BestPractice.get('key
Using AI Code Generation
1importPackage(Packages.java.awt);2importPackage(Packages.java.io);3importPackage(Packages.java.lang);4importPackage(Packages.java.util);5importPackage(Packages.java.awt.geom);6importPackage(Packages.java.awt.event);7importPackage(Packages.java.awt.image);8importPackage(Packages.java.awt.font);9importPackage(Packages.java.awt.geom);10importPackage(Packages.java.awt.geom);11importPackage(Packages.javax.swing);12importPackage(Packages.javax.swing.event);13importPackage(Packages.javax.swing.border);14importPackage(Packages.javax.swing.text);15importPackage(Packages.javax.swing.tree);16importPackage(Packages.javax.swing.table);17importPackage(Packages.javax.swing.plaf);18importPackage(Packages.javax.swing.plaf.basic);19importPackage(Packages.javax.swing.plaf.metal);20importPackage(Packages.javax.swing.plaf.synth);21importPackage(Packages.javax.swing.plaf.multi);22importPackage(Packages.javax.swing.plaf.nimbus);23importPackage(Packages.org.jfree.chart);24importPackage(Packages.org.jfree.chart.plot);25importPackage(Packages.org.jfree.chart.axis);26importPackage(Packages.org.jfree.chart.renderer.xy);27importPackage(Packages.org.jfree.chart.renderer.category);28importPackage(Packages.org.jfree.chart.renderer);29importPackage(Packages.org.jfree.chart.labels);30importPackage(Packages.org.jfree.chart.block);31importPackage(Packages.org.jfree.data.xy);32importPackage(Packages.org.jfree.data.category);33importPackage(Packages.org.jfree.chart.title);34importPackage(Packages.org.jfree.chart.entity);35importPackage(Packages.org.jfree.chart.panel);36importPackage(Packages.org.jfree.chart.needle);37importPackage(Packages.org.jfree.chart.annotations);38importPackage(Packages.org.jfree.chart.imagemap);39importPackage(Packages.org.jfree.chart.servlet);40importPackage(Packages.org.jfree.chart.encoders);41importPackage(Packages.org.jfree.chart.urls);42importPackage(Packages.org.jfree.chart.imagemap);43importPackage(Packages.org.jfree.chart.entity);44importPackage(Packages.org.jfree.chart.imagemap);45importPackage(Packages.org.jfree.chart.urls);46importPackage(Packages.org.jfree.chart.imagemap);47importPackage(Packages.org.jfree.chart.entity);48importPackage(P
Using AI Code Generation
1var BestFit = require('./BestFit.js');2BestFit.configPathSet('./config.json');3BestFit.configRead();4BestFit.getBestFit([2,4,5,6,7,8]);5var BestFit = require('./BestFit.js');6BestFit.configPathSet('./config.json');7BestFit.getBestFit([2,4,5,6,7,8]);8var BestFit = require('./BestFit.js');9BestFit.configPathSet('./config.json');10BestFit.configRead();11BestFit.getBestFit([2,4,5,6,7,8]);
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!!