How to use createScriptTransformer method in Jest

Best JavaScript code snippet using jest

ScriptTransformer.js

Source:ScriptTransformer.js Github

copy

Full Screen

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

generateEmptyCoverage.js

Source:generateEmptyCoverage.js Github

copy

Full Screen

1'use strict';2Object.defineProperty(exports, '__esModule', {3 value: true4});5exports.default = generateEmptyCoverage;6function fs() {7 const data = _interopRequireWildcard(require('graceful-fs'));8 fs = function () {9 return data;10 };11 return data;12}13function _istanbulLibCoverage() {14 const data = require('istanbul-lib-coverage');15 _istanbulLibCoverage = function () {16 return data;17 };18 return data;19}20function _istanbulLibInstrument() {21 const data = require('istanbul-lib-instrument');22 _istanbulLibInstrument = function () {23 return data;24 };25 return data;26}27function _transform() {28 const data = require('@jest/transform');29 _transform = function () {30 return data;31 };32 return data;33}34function _getRequireWildcardCache(nodeInterop) {35 if (typeof WeakMap !== 'function') return null;36 var cacheBabelInterop = new WeakMap();37 var cacheNodeInterop = new WeakMap();38 return (_getRequireWildcardCache = function (nodeInterop) {39 return nodeInterop ? cacheNodeInterop : cacheBabelInterop;40 })(nodeInterop);41}42function _interopRequireWildcard(obj, nodeInterop) {43 if (!nodeInterop && obj && obj.__esModule) {44 return obj;45 }46 if (obj === null || (typeof obj !== 'object' && typeof obj !== 'function')) {47 return {default: obj};48 }49 var cache = _getRequireWildcardCache(nodeInterop);50 if (cache && cache.has(obj)) {51 return cache.get(obj);52 }53 var newObj = {};54 var hasPropertyDescriptor =55 Object.defineProperty && Object.getOwnPropertyDescriptor;56 for (var key in obj) {57 if (key !== 'default' && Object.prototype.hasOwnProperty.call(obj, key)) {58 var desc = hasPropertyDescriptor59 ? Object.getOwnPropertyDescriptor(obj, key)60 : null;61 if (desc && (desc.get || desc.set)) {62 Object.defineProperty(newObj, key, desc);63 } else {64 newObj[key] = obj[key];65 }66 }67 }68 newObj.default = obj;69 if (cache) {70 cache.set(obj, newObj);71 }72 return newObj;73}74/**75 * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.76 *77 * This source code is licensed under the MIT license found in the78 * LICENSE file in the root directory of this source tree.79 */80async function generateEmptyCoverage(81 source,82 filename,83 globalConfig,84 config,85 changedFiles,86 sourcesRelatedToTestsInChangedFiles87) {88 const coverageOptions = {89 changedFiles,90 collectCoverage: globalConfig.collectCoverage,91 collectCoverageFrom: globalConfig.collectCoverageFrom,92 collectCoverageOnlyFrom: globalConfig.collectCoverageOnlyFrom,93 coverageProvider: globalConfig.coverageProvider,94 sourcesRelatedToTestsInChangedFiles95 };96 let coverageWorkerResult = null;97 if ((0, _transform().shouldInstrument)(filename, coverageOptions, config)) {98 if (coverageOptions.coverageProvider === 'v8') {99 const stat = fs().statSync(filename);100 return {101 kind: 'V8Coverage',102 result: {103 functions: [104 {105 functionName: '(empty-report)',106 isBlockCoverage: true,107 ranges: [108 {109 count: 0,110 endOffset: stat.size,111 startOffset: 0112 }113 ]114 }115 ],116 scriptId: '0',117 url: filename118 }119 };120 }121 const scriptTransformer = await (0, _transform().createScriptTransformer)(122 config123 ); // Transform file with instrumentation to make sure initial coverage data is well mapped to original code.124 const {code} = await scriptTransformer.transformSourceAsync(125 filename,126 source,127 {128 instrument: true,129 supportsDynamicImport: true,130 supportsExportNamespaceFrom: true,131 supportsStaticESM: true,132 supportsTopLevelAwait: true133 }134 ); // TODO: consider passing AST135 const extracted = (0, _istanbulLibInstrument().readInitialCoverage)(code); // Check extracted initial coverage is not null, this can happen when using /* istanbul ignore file */136 if (extracted) {137 coverageWorkerResult = {138 coverage: (0, _istanbulLibCoverage().createFileCoverage)(139 extracted.coverageData140 ),141 kind: 'BabelCoverage'142 };143 }144 }145 return coverageWorkerResult;...

Full Screen

Full Screen

createRuntime.js

Source:createRuntime.js Github

copy

Full Screen

...79 maxWorkers: 1,80 resetCache: false,81 }).build();82 const cacheFS = new Map();83 const scriptTransformer = await createScriptTransformer(config, cacheFS);84 const runtime = new Runtime(85 config,86 environment,87 Runtime.createResolver(config, hasteMap.moduleMap),88 scriptTransformer,89 cacheFS,90 {91 changedFiles: undefined,92 collectCoverage: false,93 collectCoverageFrom: [],94 collectCoverageOnlyFrom: undefined,95 coverageProvider: 'v8',96 sourcesRelatedToTestsInChangedFiles: undefined,97 },...

Full Screen

Full Screen

runGlobalHook.js

Source:runGlobalHook.js Github

copy

Full Screen

1'use strict';2Object.defineProperty(exports, '__esModule', {3 value: true4});5exports.default = runGlobalHook;6function util() {7 const data = _interopRequireWildcard(require('util'));8 util = function () {9 return data;10 };11 return data;12}13function _transform() {14 const data = require('@jest/transform');15 _transform = function () {16 return data;17 };18 return data;19}20function _prettyFormat() {21 const data = _interopRequireDefault(require('pretty-format'));22 _prettyFormat = function () {23 return data;24 };25 return data;26}27function _interopRequireDefault(obj) {28 return obj && obj.__esModule ? obj : {default: obj};29}30function _getRequireWildcardCache(nodeInterop) {31 if (typeof WeakMap !== 'function') return null;32 var cacheBabelInterop = new WeakMap();33 var cacheNodeInterop = new WeakMap();34 return (_getRequireWildcardCache = function (nodeInterop) {35 return nodeInterop ? cacheNodeInterop : cacheBabelInterop;36 })(nodeInterop);37}38function _interopRequireWildcard(obj, nodeInterop) {39 if (!nodeInterop && obj && obj.__esModule) {40 return obj;41 }42 if (obj === null || (typeof obj !== 'object' && typeof obj !== 'function')) {43 return {default: obj};44 }45 var cache = _getRequireWildcardCache(nodeInterop);46 if (cache && cache.has(obj)) {47 return cache.get(obj);48 }49 var newObj = {};50 var hasPropertyDescriptor =51 Object.defineProperty && Object.getOwnPropertyDescriptor;52 for (var key in obj) {53 if (key !== 'default' && Object.prototype.hasOwnProperty.call(obj, key)) {54 var desc = hasPropertyDescriptor55 ? Object.getOwnPropertyDescriptor(obj, key)56 : null;57 if (desc && (desc.get || desc.set)) {58 Object.defineProperty(newObj, key, desc);59 } else {60 newObj[key] = obj[key];61 }62 }63 }64 newObj.default = obj;65 if (cache) {66 cache.set(obj, newObj);67 }68 return newObj;69}70/**71 * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.72 *73 * This source code is licensed under the MIT license found in the74 * LICENSE file in the root directory of this source tree.75 */76async function runGlobalHook({allTests, globalConfig, moduleName}) {77 const globalModulePaths = new Set(78 allTests.map(test => test.context.config[moduleName])79 );80 if (globalConfig[moduleName]) {81 globalModulePaths.add(globalConfig[moduleName]);82 }83 if (globalModulePaths.size > 0) {84 for (const modulePath of globalModulePaths) {85 if (!modulePath) {86 continue;87 }88 const correctConfig = allTests.find(89 t => t.context.config[moduleName] === modulePath90 );91 const projectConfig = correctConfig92 ? correctConfig.context.config // Fallback to first config93 : allTests[0].context.config;94 const transformer = await (0, _transform().createScriptTransformer)(95 projectConfig96 );97 try {98 await transformer.requireAndTranspileModule(99 modulePath,100 async globalModule => {101 if (typeof globalModule !== 'function') {102 throw new TypeError(103 `${moduleName} file must export a function at ${modulePath}`104 );105 }106 await globalModule(globalConfig);107 }108 );109 } catch (error) {110 if (util().types.isNativeError(error)) {111 error.message = `Jest: Got error running ${moduleName} - ${modulePath}, reason: ${error.message}`;112 throw error;113 }114 throw new Error(115 `Jest: Got error running ${moduleName} - ${modulePath}, reason: ${(0,116 _prettyFormat().default)(error, {117 maxDepth: 3118 })}`119 );120 }121 }122 }...

Full Screen

Full Screen

index.js

Source:index.js Github

copy

Full Screen

1'use strict';2Object.defineProperty(exports, '__esModule', {3 value: true4});5Object.defineProperty(exports, 'createScriptTransformer', {6 enumerable: true,7 get: function () {8 return _ScriptTransformer.createScriptTransformer;9 }10});11Object.defineProperty(exports, 'createTranspilingRequire', {12 enumerable: true,13 get: function () {14 return _ScriptTransformer.createTranspilingRequire;15 }16});17Object.defineProperty(exports, 'handlePotentialSyntaxError', {18 enumerable: true,19 get: function () {20 return _enhanceUnexpectedTokenMessage.default;21 }22});23Object.defineProperty(exports, 'shouldInstrument', {24 enumerable: true,25 get: function () {26 return _shouldInstrument.default;27 }28});29var _ScriptTransformer = require('./ScriptTransformer');30var _shouldInstrument = _interopRequireDefault(require('./shouldInstrument'));31var _enhanceUnexpectedTokenMessage = _interopRequireDefault(32 require('./enhanceUnexpectedTokenMessage')33);34function _interopRequireDefault(obj) {35 return obj && obj.__esModule ? obj : {default: obj};...

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