How to use readCodeCacheFile method in Jest

Best JavaScript code snippet using jest

ScriptTransformer.js

Source:ScriptTransformer.js Github

copy

Full Screen

...490 const {transformer, transformerConfig = {}} =491 this._getTransformer(filename) || {};492 const cacheFilePath = this._getFileCachePath(filename, content, options);493 const sourceMapPath = cacheFilePath + '.map'; // Ignore cache if `config.cache` is set (--no-cache)494 const code = this._config.cache ? readCodeCacheFile(cacheFilePath) : null;495 if (code) {496 // This is broken: we return the code, and a path for the source map497 // directly from the cache. But, nothing ensures the source map actually498 // matches that source code. They could have gotten out-of-sync in case499 // two separate processes write concurrently to the same cache files.500 return {501 code,502 originalCode: content,503 sourceMapPath504 };505 }506 let processed = null;507 let shouldCallTransform = false;508 if (transformer && this.shouldTransform(filename)) {509 shouldCallTransform = true;510 assertSyncTransformer(transformer, this._getTransformPath(filename));511 processed = transformer.process(content, filename, {512 ...options,513 cacheFS: this._cacheFS,514 config: this._config,515 configString: this._cache.configString,516 transformerConfig517 });518 }519 return this._buildTransformResult(520 filename,521 cacheFilePath,522 content,523 transformer,524 shouldCallTransform,525 options,526 processed,527 sourceMapPath528 );529 }530 async transformSourceAsync(filepath, content, options) {531 const filename = (0, _jestUtil().tryRealpath)(filepath);532 const {transformer, transformerConfig = {}} =533 this._getTransformer(filename) || {};534 const cacheFilePath = await this._getFileCachePathAsync(535 filename,536 content,537 options538 );539 const sourceMapPath = cacheFilePath + '.map'; // Ignore cache if `config.cache` is set (--no-cache)540 const code = this._config.cache ? readCodeCacheFile(cacheFilePath) : null;541 if (code) {542 // This is broken: we return the code, and a path for the source map543 // directly from the cache. But, nothing ensures the source map actually544 // matches that source code. They could have gotten out-of-sync in case545 // two separate processes write concurrently to the same cache files.546 return {547 code,548 originalCode: content,549 sourceMapPath550 };551 }552 let processed = null;553 let shouldCallTransform = false;554 if (transformer && this.shouldTransform(filename)) {555 shouldCallTransform = true;556 const process = transformer.processAsync || transformer.process; // This is probably dead code since `_getTransformerAsync` already asserts this557 invariant(558 typeof process === 'function',559 'A transformer must always export either a `process` or `processAsync`'560 );561 processed = await process(content, filename, {562 ...options,563 cacheFS: this._cacheFS,564 config: this._config,565 configString: this._cache.configString,566 transformerConfig567 });568 }569 return this._buildTransformResult(570 filename,571 cacheFilePath,572 content,573 transformer,574 shouldCallTransform,575 options,576 processed,577 sourceMapPath578 );579 }580 async _transformAndBuildScriptAsync(581 filename,582 options,583 transformOptions,584 fileSource585 ) {586 const {isInternalModule} = options;587 let fileContent =588 fileSource !== null && fileSource !== void 0589 ? fileSource590 : this._cacheFS.get(filename);591 if (!fileContent) {592 fileContent = fs().readFileSync(filename, 'utf8');593 this._cacheFS.set(filename, fileContent);594 }595 const content = stripShebang(fileContent);596 let code = content;597 let sourceMapPath = null;598 const willTransform =599 !isInternalModule &&600 (transformOptions.instrument || this.shouldTransform(filename));601 try {602 if (willTransform) {603 const transformedSource = await this.transformSourceAsync(604 filename,605 content,606 transformOptions607 );608 code = transformedSource.code;609 sourceMapPath = transformedSource.sourceMapPath;610 }611 return {612 code,613 originalCode: content,614 sourceMapPath615 };616 } catch (e) {617 throw (0, _enhanceUnexpectedTokenMessage.default)(e);618 }619 }620 _transformAndBuildScript(filename, options, transformOptions, fileSource) {621 const {isInternalModule} = options;622 let fileContent =623 fileSource !== null && fileSource !== void 0624 ? fileSource625 : this._cacheFS.get(filename);626 if (!fileContent) {627 fileContent = fs().readFileSync(filename, 'utf8');628 this._cacheFS.set(filename, fileContent);629 }630 const content = stripShebang(fileContent);631 let code = content;632 let sourceMapPath = null;633 const willTransform =634 !isInternalModule &&635 (transformOptions.instrument || this.shouldTransform(filename));636 try {637 if (willTransform) {638 const transformedSource = this.transformSource(639 filename,640 content,641 transformOptions642 );643 code = transformedSource.code;644 sourceMapPath = transformedSource.sourceMapPath;645 }646 return {647 code,648 originalCode: content,649 sourceMapPath650 };651 } catch (e) {652 throw (0, _enhanceUnexpectedTokenMessage.default)(e);653 }654 }655 async transformAsync(filename, options, fileSource) {656 const instrument =657 options.coverageProvider === 'babel' &&658 (0, _shouldInstrument.default)(filename, options, this._config);659 const scriptCacheKey = getScriptCacheKey(filename, instrument);660 let result = this._cache.transformedFiles.get(scriptCacheKey);661 if (result) {662 return result;663 }664 result = await this._transformAndBuildScriptAsync(665 filename,666 options,667 {...options, instrument},668 fileSource669 );670 if (scriptCacheKey) {671 this._cache.transformedFiles.set(scriptCacheKey, result);672 }673 return result;674 }675 transform(filename, options, fileSource) {676 const instrument =677 options.coverageProvider === 'babel' &&678 (0, _shouldInstrument.default)(filename, options, this._config);679 const scriptCacheKey = getScriptCacheKey(filename, instrument);680 let result = this._cache.transformedFiles.get(scriptCacheKey);681 if (result) {682 return result;683 }684 result = this._transformAndBuildScript(685 filename,686 options,687 {...options, instrument},688 fileSource689 );690 if (scriptCacheKey) {691 this._cache.transformedFiles.set(scriptCacheKey, result);692 }693 return result;694 }695 transformJson(filename, options, fileSource) {696 const {isInternalModule} = options;697 const willTransform = !isInternalModule && this.shouldTransform(filename);698 if (willTransform) {699 const {code: transformedJsonSource} = this.transformSource(700 filename,701 fileSource,702 {...options, instrument: false}703 );704 return transformedJsonSource;705 }706 return fileSource;707 }708 async requireAndTranspileModule(709 moduleName,710 callback,711 options = {712 applyInteropRequireDefault: true,713 instrument: false,714 supportsDynamicImport: false,715 supportsExportNamespaceFrom: false,716 supportsStaticESM: false,717 supportsTopLevelAwait: false718 }719 ) {720 let transforming = false;721 const {applyInteropRequireDefault, ...transformOptions} = options;722 const revertHook = (0, _pirates().addHook)(723 (code, filename) => {724 try {725 transforming = true;726 return (727 this.transformSource(filename, code, transformOptions).code || code728 );729 } finally {730 transforming = false;731 }732 },733 {734 exts: this._config.moduleFileExtensions.map(ext => `.${ext}`),735 ignoreNodeModules: false,736 matcher: filename => {737 if (transforming) {738 // Don't transform any dependency required by the transformer itself739 return false;740 }741 return this.shouldTransform(filename);742 }743 }744 );745 try {746 const module = await (0, _jestUtil().requireOrImportModule)(747 moduleName,748 applyInteropRequireDefault749 );750 if (!callback) {751 revertHook();752 return module;753 }754 const cbResult = callback(module);755 if ((0, _jestUtil().isPromise)(cbResult)) {756 return waitForPromiseWithCleanup(cbResult, revertHook).then(757 () => module758 );759 }760 return module;761 } finally {762 revertHook();763 }764 }765 shouldTransform(filename) {766 const ignoreRegexp = this._cache.ignorePatternsRegExp;767 const isIgnored = ignoreRegexp ? ignoreRegexp.test(filename) : false;768 return this._config.transform.length !== 0 && !isIgnored;769 }770} // TODO: do we need to define the generics twice?771async function createTranspilingRequire(config) {772 const transformer = await createScriptTransformer(config);773 return async function requireAndTranspileModule(774 resolverPath,775 applyInteropRequireDefault = false776 ) {777 const transpiledModule = await transformer.requireAndTranspileModule(778 resolverPath,779 () => {},780 {781 applyInteropRequireDefault,782 instrument: false,783 supportsDynamicImport: false,784 // this might be true, depending on node version.785 supportsExportNamespaceFrom: false,786 supportsStaticESM: false,787 supportsTopLevelAwait: false788 }789 );790 return transpiledModule;791 };792}793const removeFile = path => {794 try {795 fs().unlinkSync(path);796 } catch {}797};798const stripShebang = content => {799 // If the file data starts with a shebang remove it. Leaves the empty line800 // to keep stack trace line numbers correct.801 if (content.startsWith('#!')) {802 return content.replace(/^#!.*/, '');803 } else {804 return content;805 }806};807/**808 * This is like `writeCacheFile` but with an additional sanity checksum. We809 * cannot use the same technique for source maps because we expose source map810 * cache file paths directly to callsites, with the expectation they can read811 * it right away. This is not a great system, because source map cache file812 * could get corrupted, out-of-sync, etc.813 */814function writeCodeCacheFile(cachePath, code) {815 const checksum = (0, _crypto().createHash)('md5').update(code).digest('hex');816 writeCacheFile(cachePath, checksum + '\n' + code);817}818/**819 * Read counterpart of `writeCodeCacheFile`. We verify that the content of the820 * file matches the checksum, in case some kind of corruption happened. This821 * could happen if an older version of `jest-runtime` writes non-atomically to822 * the same cache, for example.823 */824function readCodeCacheFile(cachePath) {825 const content = readCacheFile(cachePath);826 if (content == null) {827 return null;828 }829 const code = content.substring(33);830 const checksum = (0, _crypto().createHash)('md5').update(code).digest('hex');831 if (checksum === content.substring(0, 32)) {832 return code;833 }834 return null;835}836/**837 * Writing to the cache atomically relies on 'rename' being atomic on most838 * file systems. Doing atomic write reduces the risk of corruption by avoiding...

Full Screen

Full Screen

script_transformer.js

Source:script_transformer.js Github

copy

Full Screen

...178 mapCoverage,179 );180 let sourceMapPath = cacheFilePath + '.map';181 // Ignore cache if `config.cache` is set (--no-cache)182 let code = this._config.cache ? readCodeCacheFile(cacheFilePath) : null;183 if (code) {184 // This is broken: we return the code, and a path for the source map185 // directly from the cache. But, nothing ensures the source map actually186 // matches that source code. They could have gotten out-of-sync in case187 // two separate processes write concurrently to the same cache files.188 return {189 code,190 sourceMapPath,191 };192 }193 let transformed: TransformedSource = {194 code: content,195 map: null,196 };197 if (transform && shouldTransform(filename, this._config)) {198 const processed = transform.process(content, filename, this._config, {199 instrument,200 });201 if (typeof processed === 'string') {202 transformed.code = processed;203 } else if (processed != null && typeof processed.code === 'string') {204 transformed = processed;205 } else {206 throw new TypeError(207 "Jest: a transform's `process` function must return a string, " +208 'or an object with `code` key containing this string.',209 );210 }211 }212 if (mapCoverage) {213 if (!transformed.map) {214 const inlineSourceMap = convertSourceMap.fromSource(transformed.code);215 if (inlineSourceMap) {216 transformed.map = inlineSourceMap.toJSON();217 }218 }219 } else {220 transformed.map = null;221 }222 // That means that the transform has a custom instrumentation223 // logic and will handle it based on `config.collectCoverage` option224 const transformDidInstrument = transform && transform.canInstrument;225 if (!transformDidInstrument && instrument) {226 code = this._instrumentFile(filename, transformed.code);227 } else {228 code = transformed.code;229 }230 if (instrument && transformed.map && mapCoverage) {231 const sourceMapContent =232 typeof transformed.map === 'string'233 ? transformed.map234 : JSON.stringify(transformed.map);235 writeCacheFile(sourceMapPath, sourceMapContent);236 } else {237 sourceMapPath = null;238 }239 writeCodeCacheFile(cacheFilePath, code);240 return {241 code,242 sourceMapPath,243 };244 }245 _transformAndBuildScript(246 filename: Path,247 options: ?Options,248 instrument: boolean,249 fileSource?: string,250 ): TransformResult {251 const isInternalModule = !!(options && options.isInternalModule);252 const content = stripShebang(253 fileSource || fs.readFileSync(filename, 'utf8'),254 );255 let wrappedCode: string;256 let sourceMapPath: ?string = null;257 const willTransform =258 !isInternalModule &&259 (shouldTransform(filename, this._config) || instrument);260 try {261 if (willTransform) {262 const transformedSource = this.transformSource(263 filename,264 content,265 instrument,266 !!(options && options.mapCoverage),267 );268 wrappedCode = wrap(transformedSource.code);269 sourceMapPath = transformedSource.sourceMapPath;270 } else {271 wrappedCode = wrap(content);272 }273 return {274 script: new vm.Script(wrappedCode, {displayErrors: true, filename}),275 sourceMapPath,276 };277 } catch (e) {278 if (e.codeFrame) {279 e.stack = e.codeFrame;280 }281 throw e;282 }283 }284 transform(285 filename: Path,286 options: Options,287 fileSource?: string,288 ): TransformResult {289 const instrument = shouldInstrument(filename, options, this._config);290 const scriptCacheKey = getScriptCacheKey(291 filename,292 this._config,293 instrument,294 );295 let result = cache.get(scriptCacheKey);296 if (result) {297 return result;298 } else {299 result = this._transformAndBuildScript(300 filename,301 options,302 instrument,303 fileSource,304 );305 cache.set(scriptCacheKey, result);306 return result;307 }308 }309}310const removeFile = (path: Path) => {311 try {312 fs.unlinkSync(path);313 } catch (e) {}314};315const stripShebang = content => {316 // If the file data starts with a shebang remove it. Leaves the empty line317 // to keep stack trace line numbers correct.318 if (content.startsWith('#!')) {319 return content.replace(/^#!.*/, '');320 } else {321 return content;322 }323};324/**325 * This is like `writeCacheFile` but with an additional sanity checksum. We326 * cannot use the same technique for source maps because we expose source map327 * cache file paths directly to callsites, with the expectation they can read328 * it right away. This is not a great system, because source map cache file329 * could get corrupted, out-of-sync, etc.330 */331function writeCodeCacheFile(cachePath: Path, code: string) {332 const checksum = crypto.createHash('md5').update(code).digest('hex');333 writeCacheFile(cachePath, checksum + '\n' + code);334}335/**336 * Read counterpart of `writeCodeCacheFile`. We verify that the content of the337 * file matches the checksum, in case some kind of corruption happened. This338 * could happen if an older version of `jest-runtime` writes non-atomically to339 * the same cache, for example.340 */341function readCodeCacheFile(cachePath: Path): ?string {342 const content = readCacheFile(cachePath);343 if (content == null) {344 return null;345 }346 const code = content.substr(33);347 const checksum = crypto.createHash('md5').update(code).digest('hex');348 if (checksum === content.substr(0, 32)) {349 return code;350 }351 return null;352}353/**354 * Writing to the cache atomically relies on 'rename' being atomic on most355 * file systems. Doing atomic write reduces the risk of corruption by avoiding...

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