Best JavaScript code snippet using jest
index.js
Source:index.js
1/* eslint-disable jsdoc/no-undefined-types */2import _fs, { promises as fs } from 'fs';3import path from 'path';4import { promisify } from 'util';5import enhancedResolve from 'enhanced-resolve';6import postcss from 'postcss';7import _import from 'postcss-import';8// @ts-ignore9import _importSync from 'postcss-import-sync2';10// @ts-ignore11import allSettled from '@ungap/promise-all-settled';12/**13 * @typedef {import('sass').ImporterReturnType} sass.ImporterReturnType14 * @typedef {import('sass').Options} sass.Options15 */16/**17 * @typedef {(18 * this: { fromImport: boolean, options: { includePaths: string } },19 * url: string,20 * prev: string,21 * done?: (data: sass.ImporterReturnType) => void,22 * ) => sass.ImporterReturnType | void} Importer23 */24/**25 * @typedef {({status: 'fulfilled', value: any, reason?: undefined}|{status: 'rejected', reason: unknown, value?: undefined})} SettledResult26 */27/**28 * @param {Function[]} tasks29 *30 * @returns {SettledResult[]}31 */32function allSettledSync(tasks) {33 return tasks.map((task) => {34 try {35 return { status: 'fulfilled', value: task() };36 } catch (/** @type {any} */ error_) {37 /** @type {Error} */38 const error = error_;39 return { status: 'rejected', reason: error };40 }41 });42}43function createResolvers(sync = false) {44 const { extensions, conditionNames, mainFiles, ...resolveOptions } = {45 extensions: ['.css'],46 conditionNames: ['style', 'browser', 'import', 'require', 'node'],47 mainFields: ['style', 'browser', 'module', 'main'],48 mainFiles: ['index'],49 modules: ['node_modules']50 };51 const createResolveOptions = {52 extensions: ['.scss', ...extensions],53 conditionNames: ['sass', ...conditionNames],54 mainFiles: ['_index', ...mainFiles],55 ...resolveOptions56 };57 const createGenericResolveOptions = {58 extensions,59 conditionNames,60 mainFiles,61 ...resolveOptions62 };63 if (sync) {64 const resolve = enhancedResolve.create.sync(createResolveOptions);65 const genericResolve = enhancedResolve.create.sync(66 createGenericResolveOptions67 );68 const cssProcessor = postcss([69 _importSync({70 resolve: (71 /** @type {string} */ id,72 /** @type {string} */ basedir73 ) => genericResolve(basedir, id)74 })75 ]);76 return {77 resolve,78 genericResolve,79 cssProcessor80 };81 }82 /** @type {(basedir: string, id: string) => Promise<string>} */83 const resolve = promisify(enhancedResolve.create(createResolveOptions));84 /** @type {(basedir: string, id: string) => Promise<string>} */85 const genericResolve = promisify(86 enhancedResolve.create(createGenericResolveOptions)87 );88 // @ts-ignore89 const cssProcessor = postcss([90 _import({91 resolve: (id, basedir) => genericResolve(basedir, id)92 })93 ]);94 return {95 resolve,96 cssProcessor97 };98}99/**100 * Sass importer to import Sass modules using (enhanced) Node resolve.101 */102function api() {103 const { resolve, cssProcessor } = createResolvers();104 const { resolve: resolveSync, cssProcessor: cssProcessorSync } =105 createResolvers(true);106 /**107 * @param {string} includePaths108 */109 function asyncFunction(includePaths) {110 /** @type {Importer} */111 return async function (url, previous, _done) {112 const done = typeof _done !== 'undefined' ? _done : () => {};113 /** @type {string?} */114 let filePath = null;115 try {116 if (previous === 'stdin') {117 /** @type {SettledResult[]} */118 const filePaths = await allSettled.call(119 Promise,120 includePaths121 .split(':')122 .map((includePath) =>123 path.isAbsolute(includePath)124 ? includePath125 : path.resolve(process.cwd(), includePath)126 )127 .map((includePath) => resolve(includePath, url))128 );129 const foundFilePath = filePaths.find(130 ({ status }) => status === 'fulfilled'131 );132 filePath =133 typeof foundFilePath !== 'undefined'134 ? foundFilePath.value135 : null;136 } else {137 const foundFilePath = await resolve(138 path.dirname(previous),139 url140 );141 filePath = foundFilePath || null;142 }143 } catch (error) {144 /* istanbul ignore next */145 filePath = null;146 }147 /* istanbul ignore next */148 if (filePath === null) {149 done(null);150 return;151 }152 if (path.extname(filePath) !== '.css') {153 done({ file: filePath });154 return;155 }156 const css = await fs.readFile(filePath, 'utf8');157 if (!css.includes('@import')) {158 done({ file: filePath });159 return;160 }161 try {162 const result = await cssProcessor.process(css, {163 from: filePath164 });165 done({ contents: result.css });166 } catch (/** @type {any} */ error_) {167 /** @type {Error} */168 const error = error_;169 /* istanbul ignore next */170 done(error);171 }172 };173 }174 /**175 * @param {string} includePaths176 */177 function syncFunction(includePaths) {178 /** @type {Importer} */179 return function (url, previous) {180 /** @type {string?} */181 let filePath = null;182 try {183 if (previous === 'stdin') {184 const filePaths = allSettledSync.call(185 null,186 includePaths187 .split(':')188 .map((includePath) =>189 path.isAbsolute(includePath)190 ? includePath191 : path.resolve(process.cwd(), includePath)192 )193 .map(194 (includePath) => () =>195 resolveSync(includePath, url)196 )197 );198 const foundFilePath = filePaths.find(199 ({ status }) => status === 'fulfilled'200 );201 filePath =202 typeof foundFilePath !== 'undefined'203 ? foundFilePath.value204 : null;205 } else {206 const foundFilePath = resolveSync(207 path.dirname(previous),208 url209 );210 // @ts-ignore211 filePath = foundFilePath || null;212 }213 } catch (error) {214 /* istanbul ignore next */215 filePath = null;216 }217 /* istanbul ignore next */218 if (filePath === null) {219 return null;220 }221 if (path.extname(filePath) !== '.css') {222 return { file: filePath };223 }224 const css = _fs.readFileSync(filePath, 'utf8');225 if (!css.includes('@import')) {226 return { file: filePath };227 }228 try {229 const result = cssProcessorSync.process(css, {230 from: filePath231 });232 return { contents: result.css };233 } catch (/** @type {any} */ error_) {234 /** @type {Error} */235 const error = error_;236 /* istanbul ignore next */237 return error;238 }239 };240 }241 /**242 * @type {Importer}243 */244 function main(...arguments_) {245 const { includePaths } = this.options;246 const [url, previous, done] = arguments_;247 asyncFunction(includePaths).apply(this, [url, previous, done]);248 }249 /**250 * @type {Importer}251 */252 function sync(...arguments_) {253 const { includePaths } = this.options;254 const [url, previous] = arguments_;255 return syncFunction(includePaths).apply(this, [url, previous]);256 }257 /**258 * Sass importer to import Sass modules using (enhanced) Node resolve. Synchronous version.259 */260 main.sync = sync;261 return main;262}...
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.
|<p>it('check_object_of_Car', () => {</p><p>
expect(newCar()).toBeInstanceOf(Car);</p><p>
});</p>|
| :- |
Get 100 minutes of automation test minutes FREE!!