How to use assertSyncTransformer method in Jest

Best JavaScript code snippet using jest

ScriptTransformer.js

Source:ScriptTransformer.js Github

copy

Full Screen

...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 avoiding839 * two processes to write to the same file at the same time. It also reduces840 * the risk of reading a file that's being overwritten at the same time.841 */842const writeCacheFile = (cachePath, fileData) => {843 try {844 (0, _writeFileAtomic().sync)(cachePath, fileData, {845 encoding: 'utf8',846 fsync: false847 });848 } catch (e) {849 if (cacheWriteErrorSafeToIgnore(e, cachePath)) {850 return;851 }852 e.message =853 'jest: failed to cache transform results in: ' +854 cachePath +855 '\nFailure message: ' +856 e.message;857 removeFile(cachePath);858 throw e;859 }860};861/**862 * On Windows, renames are not atomic, leading to EPERM exceptions when two863 * processes attempt to rename to the same target file at the same time.864 * If the target file exists we can be reasonably sure another process has865 * legitimately won a cache write race and ignore the error.866 */867const cacheWriteErrorSafeToIgnore = (e, cachePath) =>868 process.platform === 'win32' &&869 e.code === 'EPERM' &&870 fs().existsSync(cachePath);871const readCacheFile = cachePath => {872 if (!fs().existsSync(cachePath)) {873 return null;874 }875 let fileData;876 try {877 fileData = fs().readFileSync(cachePath, 'utf8');878 } catch (e) {879 e.message =880 'jest: failed to read cache file: ' +881 cachePath +882 '\nFailure message: ' +883 e.message;884 removeFile(cachePath);885 throw e;886 }887 if (fileData == null) {888 // We must have somehow created the file but failed to write to it,889 // let's delete it and retry.890 removeFile(cachePath);891 }892 return fileData;893};894const getScriptCacheKey = (filename, instrument) => {895 const mtime = fs().statSync(filename).mtime;896 return filename + '_' + mtime.getTime() + (instrument ? '_instrumented' : '');897};898const calcIgnorePatternRegExp = config => {899 if (900 !config.transformIgnorePatterns ||901 config.transformIgnorePatterns.length === 0902 ) {903 return undefined;904 }905 return new RegExp(config.transformIgnorePatterns.join('|'));906};907const calcTransformRegExp = config => {908 if (!config.transform.length) {909 return undefined;910 }911 const transformRegexp = [];912 for (let i = 0; i < config.transform.length; i++) {913 transformRegexp.push([914 new RegExp(config.transform[i][0]),915 config.transform[i][1],916 config.transform[i][2]917 ]);918 }919 return transformRegexp;920};921function invariant(condition, message) {922 if (!condition) {923 throw new Error(message);924 }925}926function assertSyncTransformer(transformer, name) {927 invariant(name);928 invariant(929 typeof transformer.process === 'function',930 (0, _runtimeErrorsAndWarnings.makeInvalidSyncTransformerError)(name)931 );932}933async function createScriptTransformer(config, cacheFS = new Map()) {934 const transformer = new ScriptTransformer(config, cacheFS);935 await transformer.loadTransformers();936 return transformer;...

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