How to use verifyDirectoryExists method in Jest

Best JavaScript code snippet using jest

normalize.js

Source:normalize.js Github

copy

Full Screen

...147 ERROR,148 message,149 _utils.DOCUMENTATION_NOTE150 );151function verifyDirectoryExists(path, key) {152 try {153 const rootStat = (0, _gracefulFs().statSync)(path);154 if (!rootStat.isDirectory()) {155 throw createConfigError(156 ` ${_chalk().default.bold(path)} in the ${_chalk().default.bold(157 key158 )} option is not a directory.`159 );160 }161 } catch (err) {162 if (err instanceof _jestValidate().ValidationError) {163 throw err;164 }165 if (err.code === 'ENOENT') {166 throw createConfigError(167 ` Directory ${_chalk().default.bold(168 path169 )} in the ${_chalk().default.bold(key)} option was not found.`170 );171 } // Not sure in which cases `statSync` can throw, so let's just show the underlying error to the user172 throw createConfigError(173 ` Got an error trying to find ${_chalk().default.bold(174 path175 )} in the ${_chalk().default.bold(key)} option.\n\n Error was: ${176 err.message177 }`178 );179 }180} // TS 3.5 forces us to split these into 2181const mergeModuleNameMapperWithPreset = (options, preset) => {182 if (options['moduleNameMapper'] && preset['moduleNameMapper']) {183 options['moduleNameMapper'] = {184 ...options['moduleNameMapper'],185 ...preset['moduleNameMapper'],186 ...options['moduleNameMapper']187 };188 }189};190const mergeTransformWithPreset = (options, preset) => {191 if (options['transform'] && preset['transform']) {192 options['transform'] = {193 ...options['transform'],194 ...preset['transform'],195 ...options['transform']196 };197 }198};199const mergeGlobalsWithPreset = (options, preset) => {200 if (options['globals'] && preset['globals']) {201 options['globals'] = (0, _deepmerge().default)(202 preset['globals'],203 options['globals']204 );205 }206};207const setupPreset = (options, optionsPreset) => {208 let preset;209 const presetPath = (0, _utils.replaceRootDirInPath)(210 options.rootDir,211 optionsPreset212 );213 const presetModule = _jestResolve().default.findNodeModule(214 presetPath.startsWith('.')215 ? presetPath216 : path().join(presetPath, PRESET_NAME),217 {218 basedir: options.rootDir,219 extensions: PRESET_EXTENSIONS220 }221 );222 try {223 if (!presetModule) {224 throw new Error(`Cannot find module '${presetPath}'`);225 } // Force re-evaluation to support multiple projects226 try {227 delete require.cache[require.resolve(presetModule)];228 } catch {}229 preset = require(presetModule);230 } catch (error) {231 if (error instanceof SyntaxError || error instanceof TypeError) {232 throw createConfigError(233 ` Preset ${_chalk().default.bold(presetPath)} is invalid:\n\n ${234 error.message235 }\n ${error.stack}`236 );237 }238 if (error.message.includes('Cannot find module')) {239 if (error.message.includes(presetPath)) {240 const preset = _jestResolve().default.findNodeModule(presetPath, {241 basedir: options.rootDir242 });243 if (preset) {244 throw createConfigError(245 ` Module ${_chalk().default.bold(246 presetPath247 )} should have "jest-preset.js" or "jest-preset.json" file at the root.`248 );249 }250 throw createConfigError(251 ` Preset ${_chalk().default.bold(presetPath)} not found.`252 );253 }254 throw createConfigError(255 ` Missing dependency in ${_chalk().default.bold(presetPath)}:\n\n ${256 error.message257 }\n ${error.stack}`258 );259 }260 throw createConfigError(261 ` An unknown error occurred in ${_chalk().default.bold(262 presetPath263 )}:\n\n ${error.message}\n ${error.stack}`264 );265 }266 if (options.setupFiles) {267 options.setupFiles = (preset.setupFiles || []).concat(options.setupFiles);268 }269 if (options.setupFilesAfterEnv) {270 options.setupFilesAfterEnv = (preset.setupFilesAfterEnv || []).concat(271 options.setupFilesAfterEnv272 );273 }274 if (options.modulePathIgnorePatterns && preset.modulePathIgnorePatterns) {275 options.modulePathIgnorePatterns = preset.modulePathIgnorePatterns.concat(276 options.modulePathIgnorePatterns277 );278 }279 mergeModuleNameMapperWithPreset(options, preset);280 mergeTransformWithPreset(options, preset);281 mergeGlobalsWithPreset(options, preset);282 return {...preset, ...options};283};284const setupBabelJest = options => {285 const transform = options.transform;286 let babelJest;287 if (transform) {288 const customJSPattern = Object.keys(transform).find(pattern => {289 const regex = new RegExp(pattern);290 return regex.test('a.js') || regex.test('a.jsx');291 });292 const customTSPattern = Object.keys(transform).find(pattern => {293 const regex = new RegExp(pattern);294 return regex.test('a.ts') || regex.test('a.tsx');295 });296 [customJSPattern, customTSPattern].forEach(pattern => {297 if (pattern) {298 const customTransformer = transform[pattern];299 if (Array.isArray(customTransformer)) {300 if (customTransformer[0] === 'babel-jest') {301 babelJest = require.resolve('babel-jest');302 customTransformer[0] = babelJest;303 } else if (customTransformer[0].includes('babel-jest')) {304 babelJest = customTransformer[0];305 }306 } else {307 if (customTransformer === 'babel-jest') {308 babelJest = require.resolve('babel-jest');309 transform[pattern] = babelJest;310 } else if (customTransformer.includes('babel-jest')) {311 babelJest = customTransformer;312 }313 }314 }315 });316 } else {317 babelJest = require.resolve('babel-jest');318 options.transform = {319 [_constants.DEFAULT_JS_PATTERN]: babelJest320 };321 }322};323const normalizeCollectCoverageOnlyFrom = (options, key) => {324 const initialCollectCoverageFrom = options[key];325 const collectCoverageOnlyFrom = Array.isArray(initialCollectCoverageFrom)326 ? initialCollectCoverageFrom // passed from argv327 : Object.keys(initialCollectCoverageFrom); // passed from options328 return collectCoverageOnlyFrom.reduce((map, filePath) => {329 filePath = path().resolve(330 options.rootDir,331 (0, _utils.replaceRootDirInPath)(options.rootDir, filePath)332 );333 map[filePath] = true;334 return map;335 }, Object.create(null));336};337const normalizeCollectCoverageFrom = (options, key) => {338 const initialCollectCoverageFrom = options[key];339 let value;340 if (!initialCollectCoverageFrom) {341 value = [];342 }343 if (!Array.isArray(initialCollectCoverageFrom)) {344 try {345 value = JSON.parse(initialCollectCoverageFrom);346 } catch {}347 if (options[key] && !Array.isArray(value)) {348 value = [initialCollectCoverageFrom];349 }350 } else {351 value = initialCollectCoverageFrom;352 }353 if (value) {354 value = value.map(filePath =>355 filePath.replace(/^(!?)(<rootDir>\/)(.*)/, '$1$3')356 );357 }358 return value;359};360const normalizeUnmockedModulePathPatterns = (361 options,362 key // _replaceRootDirTags is specifically well-suited for substituting363) =>364 // <rootDir> in paths (it deals with properly interpreting relative path365 // separators, etc).366 //367 // For patterns, direct global substitution is far more ideal, so we368 // special case substitutions for patterns here.369 options[key].map(pattern =>370 (0, _jestRegexUtil().replacePathSepForRegex)(371 pattern.replace(/<rootDir>/g, options.rootDir)372 )373 );374const normalizePreprocessor = options => {375 if (options.scriptPreprocessor && options.transform) {376 throw createConfigError(` Options: ${_chalk().default.bold(377 'scriptPreprocessor'378 )} and ${_chalk().default.bold('transform')} cannot be used together.379 Please change your configuration to only use ${_chalk().default.bold(380 'transform'381 )}.`);382 }383 if (options.preprocessorIgnorePatterns && options.transformIgnorePatterns) {384 throw createConfigError(` Options ${_chalk().default.bold(385 'preprocessorIgnorePatterns'386 )} and ${_chalk().default.bold(387 'transformIgnorePatterns'388 )} cannot be used together.389 Please change your configuration to only use ${_chalk().default.bold(390 'transformIgnorePatterns'391 )}.`);392 }393 if (options.scriptPreprocessor) {394 options.transform = {395 '.*': options.scriptPreprocessor396 };397 }398 if (options.preprocessorIgnorePatterns) {399 options.transformIgnorePatterns = options.preprocessorIgnorePatterns;400 }401 delete options.scriptPreprocessor;402 delete options.preprocessorIgnorePatterns;403 return options;404};405const normalizeMissingOptions = (options, configPath, projectIndex) => {406 if (!options.name) {407 options.name = (0, _crypto().createHash)('md5')408 .update(options.rootDir) // In case we load config from some path that has the same root dir409 .update(configPath || '')410 .update(String(projectIndex))411 .digest('hex');412 }413 if (!options.setupFiles) {414 options.setupFiles = [];415 }416 return options;417};418const normalizeRootDir = options => {419 // Assert that there *is* a rootDir420 if (!options.rootDir) {421 throw createConfigError(422 ` Configuration option ${_chalk().default.bold(423 'rootDir'424 )} must be specified.`425 );426 }427 options.rootDir = path().normalize(options.rootDir);428 try {429 // try to resolve windows short paths, ignoring errors (permission errors, mostly)430 options.rootDir = (0, _jestUtil().tryRealpath)(options.rootDir);431 } catch {432 // ignored433 }434 verifyDirectoryExists(options.rootDir, 'rootDir');435 return {...options, rootDir: options.rootDir};436};437const normalizeReporters = options => {438 const reporters = options.reporters;439 if (!reporters || !Array.isArray(reporters)) {440 return options;441 }442 (0, _ReporterValidationErrors.validateReporters)(reporters);443 options.reporters = reporters.map(reporterConfig => {444 const normalizedReporterConfig =445 typeof reporterConfig === 'string' // if reporter config is a string, we wrap it in an array446 ? // and pass an empty object for options argument, to normalize447 // the shape.448 [reporterConfig, {}]449 : reporterConfig;450 const reporterPath = (0, _utils.replaceRootDirInPath)(451 options.rootDir,452 normalizedReporterConfig[0]453 );454 if (reporterPath !== _constants.DEFAULT_REPORTER_LABEL) {455 const reporter = _jestResolve().default.findNodeModule(reporterPath, {456 basedir: options.rootDir457 });458 if (!reporter) {459 throw new (_jestResolve().default.ModuleNotFoundError)(460 `Could not resolve a module for a custom reporter.\n` +461 ` Module name: ${reporterPath}`462 );463 }464 normalizedReporterConfig[0] = reporter;465 }466 return normalizedReporterConfig;467 });468 return options;469};470const buildTestPathPattern = argv => {471 const patterns = [];472 if (argv._) {473 patterns.push(...argv._);474 }475 if (argv.testPathPattern) {476 patterns.push(...argv.testPathPattern);477 }478 const replacePosixSep = pattern => {479 // yargs coerces positional args into numbers480 const patternAsString = pattern.toString();481 if (path().sep === '/') {482 return patternAsString;483 }484 return patternAsString.replace(/\//g, '\\\\');485 };486 const testPathPattern = patterns.map(replacePosixSep).join('|');487 if ((0, _validatePattern.default)(testPathPattern)) {488 return testPathPattern;489 } else {490 showTestPathPatternError(testPathPattern);491 return '';492 }493};494const showTestPathPatternError = testPathPattern => {495 (0, _jestUtil().clearLine)(process.stdout);496 console.log(497 _chalk().default.red(498 ` Invalid testPattern ${testPathPattern} supplied. ` +499 `Running all tests instead.`500 )501 );502};503function normalize(initialOptions, argv, configPath, projectIndex = Infinity) {504 const {hasDeprecationWarnings} = (0, _jestValidate().validate)(505 initialOptions,506 {507 comment: _utils.DOCUMENTATION_NOTE,508 deprecatedConfig: _Deprecated.default,509 exampleConfig: _ValidConfig.default,510 recursiveBlacklist: [511 'collectCoverageOnlyFrom', // 'coverageThreshold' allows to use 'global' and glob strings on the same512 // level, there's currently no way we can deal with such config513 'coverageThreshold',514 'globals',515 'moduleNameMapper',516 'testEnvironmentOptions',517 'transform'518 ]519 }520 );521 let options = normalizePreprocessor(522 normalizeReporters(523 normalizeMissingOptions(524 normalizeRootDir((0, _setFromArgv.default)(initialOptions, argv)),525 configPath,526 projectIndex527 )528 )529 );530 if (options.preset) {531 options = setupPreset(options, options.preset);532 }533 if (!options.setupFilesAfterEnv) {534 options.setupFilesAfterEnv = [];535 }536 if (537 options.setupTestFrameworkScriptFile &&538 options.setupFilesAfterEnv.length > 0539 ) {540 throw createConfigError(` Options: ${_chalk().default.bold(541 'setupTestFrameworkScriptFile'542 )} and ${_chalk().default.bold(543 'setupFilesAfterEnv'544 )} cannot be used together.545 Please change your configuration to only use ${_chalk().default.bold(546 'setupFilesAfterEnv'547 )}.`);548 }549 if (options.setupTestFrameworkScriptFile) {550 options.setupFilesAfterEnv.push(options.setupTestFrameworkScriptFile);551 }552 options.testEnvironment = (0, _utils.getTestEnvironment)({553 rootDir: options.rootDir,554 testEnvironment:555 options.testEnvironment || _Defaults.default.testEnvironment556 });557 if (!options.roots && options.testPathDirs) {558 options.roots = options.testPathDirs;559 delete options.testPathDirs;560 }561 if (!options.roots) {562 options.roots = [options.rootDir];563 }564 if (!options.testRunner || options.testRunner === 'jasmine2') {565 options.testRunner = require.resolve('jest-jasmine2');566 }567 if (!options.coverageDirectory) {568 options.coverageDirectory = path().resolve(options.rootDir, 'coverage');569 }570 setupBabelJest(options); // TODO: Type this properly571 const newOptions = {..._Defaults.default};572 if (options.resolver) {573 newOptions.resolver = (0, _utils.resolve)(null, {574 filePath: options.resolver,575 key: 'resolver',576 rootDir: options.rootDir577 });578 }579 const optionKeys = Object.keys(options);580 optionKeys.reduce((newOptions, key) => {581 // The resolver has been resolved separately; skip it582 if (key === 'resolver') {583 return newOptions;584 } // This is cheating, because it claims that all keys of InitialOptions are Required.585 // We only really know it's Required for oldOptions[key], not for oldOptions.someOtherKey,586 // so oldOptions[key] is the only way it should be used.587 const oldOptions = options;588 let value;589 switch (key) {590 case 'collectCoverageOnlyFrom':591 value = normalizeCollectCoverageOnlyFrom(oldOptions, key);592 break;593 case 'setupFiles':594 case 'setupFilesAfterEnv':595 case 'snapshotSerializers':596 {597 const option = oldOptions[key];598 value =599 option &&600 option.map(filePath =>601 (0, _utils.resolve)(newOptions.resolver, {602 filePath,603 key,604 rootDir: options.rootDir605 })606 );607 }608 break;609 case 'modulePaths':610 case 'roots':611 {612 const option = oldOptions[key];613 value =614 option &&615 option.map(filePath =>616 path().resolve(617 options.rootDir,618 (0, _utils.replaceRootDirInPath)(options.rootDir, filePath)619 )620 );621 }622 break;623 case 'collectCoverageFrom':624 value = normalizeCollectCoverageFrom(oldOptions, key);625 break;626 case 'cacheDirectory':627 case 'coverageDirectory':628 {629 const option = oldOptions[key];630 value =631 option &&632 path().resolve(633 options.rootDir,634 (0, _utils.replaceRootDirInPath)(options.rootDir, option)635 );636 }637 break;638 case 'dependencyExtractor':639 case 'globalSetup':640 case 'globalTeardown':641 case 'moduleLoader':642 case 'snapshotResolver':643 case 'testResultsProcessor':644 case 'testRunner':645 case 'filter':646 {647 const option = oldOptions[key];648 value =649 option &&650 (0, _utils.resolve)(newOptions.resolver, {651 filePath: option,652 key,653 rootDir: options.rootDir654 });655 }656 break;657 case 'runner':658 {659 const option = oldOptions[key];660 value =661 option &&662 (0, _utils.getRunner)(newOptions.resolver, {663 filePath: option,664 rootDir: options.rootDir665 });666 }667 break;668 case 'prettierPath':669 {670 // We only want this to throw if "prettierPath" is explicitly passed671 // from config or CLI, and the requested path isn't found. Otherwise we672 // set it to null and throw an error lazily when it is used.673 const option = oldOptions[key];674 value =675 option &&676 (0, _utils.resolve)(newOptions.resolver, {677 filePath: option,678 key,679 optional: option === _Defaults.default[key],680 rootDir: options.rootDir681 });682 }683 break;684 case 'moduleNameMapper':685 const moduleNameMapper = oldOptions[key];686 value =687 moduleNameMapper &&688 Object.keys(moduleNameMapper).map(regex => {689 const item = moduleNameMapper && moduleNameMapper[regex];690 return (691 item && [692 regex,693 (0, _utils._replaceRootDirTags)(options.rootDir, item)694 ]695 );696 });697 break;698 case 'transform':699 const transform = oldOptions[key];700 value =701 transform &&702 Object.keys(transform).map(regex => {703 const transformElement = transform[regex];704 return [705 regex,706 (0, _utils.resolve)(newOptions.resolver, {707 filePath: Array.isArray(transformElement)708 ? transformElement[0]709 : transformElement,710 key,711 rootDir: options.rootDir712 }),713 Array.isArray(transformElement) ? transformElement[1] : {}714 ];715 });716 break;717 case 'coveragePathIgnorePatterns':718 case 'modulePathIgnorePatterns':719 case 'testPathIgnorePatterns':720 case 'transformIgnorePatterns':721 case 'watchPathIgnorePatterns':722 case 'unmockedModulePathPatterns':723 value = normalizeUnmockedModulePathPatterns(oldOptions, key);724 break;725 case 'haste':726 value = {...oldOptions[key]};727 if (value.hasteImplModulePath != null) {728 const resolvedHasteImpl = (0, _utils.resolve)(newOptions.resolver, {729 filePath: (0, _utils.replaceRootDirInPath)(730 options.rootDir,731 value.hasteImplModulePath732 ),733 key: 'haste.hasteImplModulePath',734 rootDir: options.rootDir735 });736 value.hasteImplModulePath = resolvedHasteImpl || undefined;737 }738 break;739 case 'projects':740 value = (oldOptions[key] || [])741 .map(project =>742 typeof project === 'string'743 ? (0, _utils._replaceRootDirTags)(options.rootDir, project)744 : project745 )746 .reduce((projects, project) => {747 // Project can be specified as globs. If a glob matches any files,748 // We expand it to these paths. If not, we keep the original path749 // for the future resolution.750 const globMatches =751 typeof project === 'string' ? (0, _glob().sync)(project) : [];752 return projects.concat(globMatches.length ? globMatches : project);753 }, []);754 break;755 case 'moduleDirectories':756 case 'testMatch':757 {758 const replacedRootDirTags = (0, _utils._replaceRootDirTags)(759 (0, _utils.escapeGlobCharacters)(options.rootDir),760 oldOptions[key]761 );762 if (replacedRootDirTags) {763 value = Array.isArray(replacedRootDirTags)764 ? replacedRootDirTags.map(_jestUtil().replacePathSepForGlob)765 : (0, _jestUtil().replacePathSepForGlob)(replacedRootDirTags);766 } else {767 value = replacedRootDirTags;768 }769 }770 break;771 case 'testRegex':772 {773 const option = oldOptions[key];774 value = option775 ? (Array.isArray(option) ? option : [option]).map(776 _jestRegexUtil().replacePathSepForRegex777 )778 : [];779 }780 break;781 case 'moduleFileExtensions': {782 value = oldOptions[key];783 if (784 Array.isArray(value) && // If it's the wrong type, it can throw at a later time785 (options.runner === undefined ||786 options.runner === _Defaults.default.runner) && // Only require 'js' for the default jest-runner787 !value.includes('js')788 ) {789 const errorMessage =790 ` moduleFileExtensions must include 'js':\n` +791 ` but instead received:\n` +792 ` ${_chalk().default.bold.red(JSON.stringify(value))}`; // If `js` is not included, any dependency Jest itself injects into793 // the environment, like jasmine or sourcemap-support, will need to794 // `require` its modules with a file extension. This is not plausible795 // in the long run, so it's way easier to just fail hard early.796 // We might consider throwing if `json` is missing as well, as it's a797 // fair assumption from modules that they can do798 // `require('some-package/package') without the trailing `.json` as it799 // works in Node normally.800 throw createConfigError(801 errorMessage +802 "\n Please change your configuration to include 'js'."803 );804 }805 break;806 }807 case 'bail': {808 const bail = oldOptions[key];809 if (typeof bail === 'boolean') {810 value = bail ? 1 : 0;811 } else if (typeof bail === 'string') {812 value = 1; // If Jest is invoked as `jest --bail someTestPattern` then need to813 // move the pattern from the `bail` configuration and into `argv._`814 // to be processed as an extra parameter815 argv._.push(bail);816 } else {817 value = oldOptions[key];818 }819 break;820 }821 case 'displayName': {822 const displayName = oldOptions[key];823 /**824 * Ensuring that displayName shape is correct here so that the825 * reporters can trust the shape of the data826 */827 if (typeof displayName === 'object') {828 const {name, color} = displayName;829 if (830 !name ||831 !color ||832 typeof name !== 'string' ||833 typeof color !== 'string'834 ) {835 const errorMessage =836 ` Option "${_chalk().default.bold(837 'displayName'838 )}" must be of type:\n\n` +839 ' {\n' +840 ' name: string;\n' +841 ' color: string;\n' +842 ' }\n';843 throw createConfigError(errorMessage);844 }845 value = oldOptions[key];846 } else {847 value = {848 color: (0, _color.getDisplayNameColor)(options.runner),849 name: displayName850 };851 }852 break;853 }854 case 'testTimeout': {855 if (oldOptions[key] < 0) {856 throw createConfigError(857 ` Option "${_chalk().default.bold(858 'testTimeout'859 )}" must be a natural number.`860 );861 }862 value = oldOptions[key];863 break;864 }865 case 'automock':866 case 'cache':867 case 'changedSince':868 case 'changedFilesWithAncestor':869 case 'clearMocks':870 case 'collectCoverage':871 case 'coverageProvider':872 case 'coverageReporters':873 case 'coverageThreshold':874 case 'detectLeaks':875 case 'detectOpenHandles':876 case 'errorOnDeprecated':877 case 'expand':878 case 'extraGlobals':879 case 'globals':880 case 'findRelatedTests':881 case 'forceCoverageMatch':882 case 'forceExit':883 case 'injectGlobals':884 case 'lastCommit':885 case 'listTests':886 case 'logHeapUsage':887 case 'maxConcurrency':888 case 'mapCoverage':889 case 'name':890 case 'noStackTrace':891 case 'notify':892 case 'notifyMode':893 case 'onlyChanged':894 case 'onlyFailures':895 case 'outputFile':896 case 'passWithNoTests':897 case 'replname':898 case 'reporters':899 case 'resetMocks':900 case 'resetModules':901 case 'restoreMocks':902 case 'rootDir':903 case 'runTestsByPath':904 case 'silent':905 case 'skipFilter':906 case 'skipNodeResolution':907 case 'slowTestThreshold':908 case 'testEnvironment':909 case 'testEnvironmentOptions':910 case 'testFailureExitCode':911 case 'testLocationInResults':912 case 'testNamePattern':913 case 'testURL':914 case 'timers':915 case 'useStderr':916 case 'verbose':917 case 'watch':918 case 'watchAll':919 case 'watchman':920 value = oldOptions[key];921 break;922 case 'watchPlugins':923 value = (oldOptions[key] || []).map(watchPlugin => {924 if (typeof watchPlugin === 'string') {925 return {926 config: {},927 path: (0, _utils.getWatchPlugin)(newOptions.resolver, {928 filePath: watchPlugin,929 rootDir: options.rootDir930 })931 };932 } else {933 return {934 config: watchPlugin[1] || {},935 path: (0, _utils.getWatchPlugin)(newOptions.resolver, {936 filePath: watchPlugin[0],937 rootDir: options.rootDir938 })939 };940 }941 });942 break;943 } // @ts-expect-error: automock is missing in GlobalConfig, so what944 newOptions[key] = value;945 return newOptions;946 }, newOptions);947 newOptions.roots.forEach((root, i) => {948 verifyDirectoryExists(root, `roots[${i}]`);949 });950 try {951 // try to resolve windows short paths, ignoring errors (permission errors, mostly)952 newOptions.cwd = (0, _jestUtil().tryRealpath)(process.cwd());953 } catch {954 // ignored955 }956 newOptions.testSequencer = (0, _utils.getSequencer)(newOptions.resolver, {957 filePath: options.testSequencer || _Defaults.default.testSequencer,958 rootDir: options.rootDir959 });960 newOptions.nonFlagArgs = argv._;961 newOptions.testPathPattern = buildTestPathPattern(argv);962 newOptions.json = !!argv.json;...

Full Screen

Full Screen

index.js

Source:index.js Github

copy

Full Screen

...217 const fileContents = await fsPromises.readFile(configFile, { encoding: 'utf-8' });218 const json = JSON.parse(fileContents);219 return json;220}221function verifyDirectoryExists(directory) {222 return new Promise((resolve, reject) => {223 fsPromises224 .access(directory, fs.constants.F_OK || fs.constants.W_OK)225 .then(() => resolve())226 .catch((error) => {227 console.error(`Directory "${directory}" don't exists`);228 reject(error);229 });230 });231}232function getArgv() {233 const { argv } = yargs(hideBin(process.argv))234 .option('directory', {235 alias: 'd',236 type: 'string',237 description: 'Directory to look for files',238 demandOption: 'Please specify a directory to look for files'239 })240 .option('config', {241 alias: 'c',242 type: 'string',243 description: 'Configuration file (JSON)',244 demandOption: 'Please specify a config file'245 })246 .usage('Usage: $0 -d [directory] -c [config file]')247 .demandOption(['d', 'c']);248 return argv;249}250async function main() {251 const argv = getArgv();252 try {253 await verifyDirectoryExists(argv.directory);254 const config = await parseConfigFile(argv.config);255 const files = await readAllFilesRecursivelly('**/*.mkv', argv.directory);256 await Promise.all(257 Object.entries(config.episodes).map(async ([episodeIdentifier, episodeName]) =>258 lookup(config.meta, files, episodeIdentifier, episodeName)259 )260 );261 console.table(tableItems);262 } catch (er) {263 console.error(er);264 }265 console.log('<<<END>>>');266}267main();

Full Screen

Full Screen

DownloadContent.js

Source:DownloadContent.js Github

copy

Full Screen

...68 * @return {Promise<{type:string,name:string,data:[]}>}69 */70 async scrape({ html, url }) {71 if (!this.directoryVerified) {72 await verifyDirectoryExists(73 this.config.filePath || this.scraper.config.filePath74 );75 this.directoryVerified = true;76 }77 this.config.contentType = this.config.contentType || "image";78 var $ = cheerio.load(html);79 const baseUrlFromBaseTag = getBaseUrlFromBaseTag(80 $,81 this.scraper.config.baseSiteUrl82 );83 const elementList = await createElementList($, this.querySelector, {84 condition: this.config.condition,85 slice: this.config.slice,86 });...

Full Screen

Full Screen

Scraper.js

Source:Scraper.js Github

copy

Full Screen

...167 * @param {string} fileName 168 * @return {Promise<void>} 169 */170 saveFile(data, fileName) {171 // verifyDirectoryExists(this.config.logPath);172 return new Promise(async (resolve, reject) => {173 await verifyDirectoryExists(this.config.logPath);174 // this.log('saving file')175 // debugger;176 fs.writeFile(path.join(this.config.logPath, `${fileName}.json`), JSON.stringify(data), (error) => {177 if (error) {178 reject(error)179 } else {180 this.log(`Log file ${fileName} saved`);181 resolve();182 }183 });184 })185 }186 /**187 * @return {Promise<void>}...

Full Screen

Full Screen

files.js

Source:files.js Github

copy

Full Screen

1const fs = require('fs');2// const {promisify} = require('util');3// const access = promisify(fs.access);4// const mkdir = promisify(fs.mkdir);5function verifyDirectoryExists(path) {//Will make sure the target directory exists. 6 if (!fs.existsSync(path)) {7 // console.log('creating dir:', path)8 fs.mkdirSync(path,{recursive:true});9 }10}11// async function verifyDirectoryExists(path){12 13// try {14// await access(path); 15// } catch (error) {16// console.log('error from verify',error)17// try {18// await mkdir(path); 19// } catch (error) {20// if(error.code !== 'EEXIST'){21// throw error;22// }23// // debugger24// }25 ...

Full Screen

Full Screen

Jest Testing Tutorial

LambdaTest’s Jest Testing Tutorial covers step-by-step guides around Jest with code examples to help you be proficient with the Jest framework. The Jest tutorial has chapters to help you learn right from the basics of Jest framework to code-based tutorials around testing react apps with Jest, perform snapshot testing, import ES modules and more.

Chapters

  1. What is Jest Framework
  2. Advantages of Jest - Jest has 3,898,000 GitHub repositories, as mentioned on its official website. Learn what makes Jest special and why Jest has gained popularity among the testing and developer community.
  3. Jest Installation - All the prerequisites and set up steps needed to help you start Jest automation testing.
  4. Using Jest with NodeJS Project - Learn how to leverage Jest framework to automate testing using a NodeJS Project.
  5. Writing First Test for Jest Framework - Get started with code-based tutorial to help you write and execute your first Jest framework testing script.
  6. Jest Vocabulary - Learn the industry renowned and official jargons of the Jest framework by digging deep into the Jest vocabulary.
  7. Unit Testing with Jest - Step-by-step tutorial to help you execute unit testing with Jest framework.
  8. Jest Basics - Learn about the most pivotal and basic features which makes Jest special.
  9. Jest Parameterized Tests - Avoid code duplication and fasten automation testing with Jest using parameterized tests. Parameterization allows you to trigger the same test scenario over different test configurations by incorporating parameters.
  10. Jest Matchers - Enforce assertions better with the help of matchers. Matchers help you compare the actual output with the expected one. Here is an example to see if the object is acquired from the correct class or not. -

|<p>it('check_object_of_Car', () => {</p><p> expect(newCar()).toBeInstanceOf(Car);</p><p> });</p>| | :- |

  1. Jest Hooks: Setup and Teardown - Learn how to set up conditions which needs to be followed by the test execution and incorporate a tear down function to free resources after the execution is complete.
  2. Jest Code Coverage - Unsure there is no code left unchecked in your application. Jest gives a specific flag called --coverage to help you generate code coverage.
  3. HTML Report Generation - Learn how to create a comprehensive HTML report based on your Jest test execution.
  4. Testing React app using Jest Framework - Learn how to test your react web-application with Jest framework in this detailed Jest tutorial.
  5. Test using LambdaTest cloud Selenium Grid - Run your Jest testing script over LambdaTest cloud-based platform and leverage parallel testing to help trim down your test execution time.
  6. Snapshot Testing for React Front Ends - Capture screenshots of your react based web-application and compare them automatically for visual anomalies with the help of Jest tutorial.
  7. Bonus: Import ES modules with Jest - ES modules are also known as ECMAScript modules. Learn how to best use them by importing in your Jest testing scripts.
  8. Jest vs Mocha vs Jasmine - Learn the key differences between the most popular JavaScript-based testing frameworks i.e. Jest, Mocha, and Jasmine.
  9. Jest FAQs(Frequently Asked Questions) - Explore the most commonly asked questions around Jest framework, with their answers.

Run Jest automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful