How to use createResolveOptions method in Jest

Best JavaScript code snippet using jest

index.js

Source:index.js Github

copy

Full Screen

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}...

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