How to use requireOrImportModule method in Jest

Best JavaScript code snippet using jest

runJest.js

Source:runJest.js Github

copy

Full Screen

1'use strict';2Object.defineProperty(exports, '__esModule', {3 value: true4});5exports.default = runJest;6function path() {7 const data = _interopRequireWildcard(require('path'));8 path = function () {9 return data;10 };11 return data;12}13function _chalk() {14 const data = _interopRequireDefault(require('chalk'));15 _chalk = function () {16 return data;17 };18 return data;19}20function _exit() {21 const data = _interopRequireDefault(require('exit'));22 _exit = function () {23 return data;24 };25 return data;26}27function fs() {28 const data = _interopRequireWildcard(require('graceful-fs'));29 fs = function () {30 return data;31 };32 return data;33}34function _console() {35 const data = require('@jest/console');36 _console = function () {37 return data;38 };39 return data;40}41function _testResult() {42 const data = require('@jest/test-result');43 _testResult = function () {44 return data;45 };46 return data;47}48function _jestResolve() {49 const data = _interopRequireDefault(require('jest-resolve'));50 _jestResolve = function () {51 return data;52 };53 return data;54}55function _jestUtil() {56 const data = require('jest-util');57 _jestUtil = function () {58 return data;59 };60 return data;61}62function _jestWatcher() {63 const data = require('jest-watcher');64 _jestWatcher = function () {65 return data;66 };67 return data;68}69var _SearchSource = _interopRequireDefault(require('./SearchSource'));70var _TestScheduler = require('./TestScheduler');71var _collectHandles = _interopRequireDefault(require('./collectHandles'));72var _getNoTestsFoundMessage = _interopRequireDefault(73 require('./getNoTestsFoundMessage')74);75var _runGlobalHook = _interopRequireDefault(require('./runGlobalHook'));76function _interopRequireDefault(obj) {77 return obj && obj.__esModule ? obj : {default: obj};78}79function _getRequireWildcardCache(nodeInterop) {80 if (typeof WeakMap !== 'function') return null;81 var cacheBabelInterop = new WeakMap();82 var cacheNodeInterop = new WeakMap();83 return (_getRequireWildcardCache = function (nodeInterop) {84 return nodeInterop ? cacheNodeInterop : cacheBabelInterop;85 })(nodeInterop);86}87function _interopRequireWildcard(obj, nodeInterop) {88 if (!nodeInterop && obj && obj.__esModule) {89 return obj;90 }91 if (obj === null || (typeof obj !== 'object' && typeof obj !== 'function')) {92 return {default: obj};93 }94 var cache = _getRequireWildcardCache(nodeInterop);95 if (cache && cache.has(obj)) {96 return cache.get(obj);97 }98 var newObj = {};99 var hasPropertyDescriptor =100 Object.defineProperty && Object.getOwnPropertyDescriptor;101 for (var key in obj) {102 if (key !== 'default' && Object.prototype.hasOwnProperty.call(obj, key)) {103 var desc = hasPropertyDescriptor104 ? Object.getOwnPropertyDescriptor(obj, key)105 : null;106 if (desc && (desc.get || desc.set)) {107 Object.defineProperty(newObj, key, desc);108 } else {109 newObj[key] = obj[key];110 }111 }112 }113 newObj.default = obj;114 if (cache) {115 cache.set(obj, newObj);116 }117 return newObj;118}119/**120 * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.121 *122 * This source code is licensed under the MIT license found in the123 * LICENSE file in the root directory of this source tree.124 */125const getTestPaths = async (126 globalConfig,127 source,128 outputStream,129 changedFiles,130 jestHooks,131 filter132) => {133 const data = await source.getTestPaths(globalConfig, changedFiles, filter);134 if (!data.tests.length && globalConfig.onlyChanged && data.noSCM) {135 new (_console().CustomConsole)(outputStream, outputStream).log(136 'Jest can only find uncommitted changed files in a git or hg ' +137 'repository. If you make your project a git or hg ' +138 'repository (`git init` or `hg init`), Jest will be able ' +139 'to only run tests related to files changed since the last ' +140 'commit.'141 );142 }143 const shouldTestArray = await Promise.all(144 data.tests.map(test =>145 jestHooks.shouldRunTestSuite({146 config: test.context.config,147 duration: test.duration,148 testPath: test.path149 })150 )151 );152 const filteredTests = data.tests.filter((_test, i) => shouldTestArray[i]);153 return {...data, allTests: filteredTests.length, tests: filteredTests};154};155const processResults = async (runResults, options) => {156 const {157 outputFile,158 json: isJSON,159 onComplete,160 outputStream,161 testResultsProcessor,162 collectHandles163 } = options;164 if (collectHandles) {165 runResults.openHandles = await collectHandles();166 } else {167 runResults.openHandles = [];168 }169 if (testResultsProcessor) {170 const processor = await (0, _jestUtil().requireOrImportModule)(171 testResultsProcessor172 );173 runResults = processor(runResults);174 }175 if (isJSON) {176 if (outputFile) {177 const cwd = (0, _jestUtil().tryRealpath)(process.cwd());178 const filePath = path().resolve(cwd, outputFile);179 fs().writeFileSync(180 filePath,181 JSON.stringify((0, _testResult().formatTestResults)(runResults))182 );183 outputStream.write(184 `Test results written to: ${path().relative(cwd, filePath)}\n`185 );186 } else {187 process.stdout.write(188 JSON.stringify((0, _testResult().formatTestResults)(runResults))189 );190 }191 }192 onComplete === null || onComplete === void 0193 ? void 0194 : onComplete(runResults);195};196const testSchedulerContext = {197 firstRun: true,198 previousSuccess: true199};200async function runJest({201 contexts,202 globalConfig,203 outputStream,204 testWatcher,205 jestHooks = new (_jestWatcher().JestHook)().getEmitter(),206 startRun,207 changedFilesPromise,208 onComplete,209 failedTestsCache,210 filter211}) {212 // Clear cache for required modules - there might be different resolutions213 // from Jest's config loading to running the tests214 _jestResolve().default.clearDefaultResolverCache();215 const Sequencer = await (0, _jestUtil().requireOrImportModule)(216 globalConfig.testSequencer217 );218 const sequencer = new Sequencer();219 let allTests = [];220 if (changedFilesPromise && globalConfig.watch) {221 const {repos} = await changedFilesPromise;222 const noSCM = Object.keys(repos).every(scm => repos[scm].size === 0);223 if (noSCM) {224 process.stderr.write(225 '\n' +226 _chalk().default.bold('--watch') +227 ' is not supported without git/hg, please use --watchAll ' +228 '\n'229 );230 (0, _exit().default)(1);231 }232 }233 const searchSources = contexts.map(234 context => new _SearchSource.default(context)235 );236 const testRunData = await Promise.all(237 contexts.map(async (context, index) => {238 const searchSource = searchSources[index];239 const matches = await getTestPaths(240 globalConfig,241 searchSource,242 outputStream,243 changedFilesPromise && (await changedFilesPromise),244 jestHooks,245 filter246 );247 allTests = allTests.concat(matches.tests);248 return {249 context,250 matches251 };252 })253 );254 allTests = await sequencer.sort(allTests);255 if (globalConfig.listTests) {256 const testsPaths = Array.from(new Set(allTests.map(test => test.path)));257 /* eslint-disable no-console */258 if (globalConfig.json) {259 console.log(JSON.stringify(testsPaths));260 } else {261 console.log(testsPaths.join('\n'));262 }263 /* eslint-enable */264 onComplete &&265 onComplete((0, _testResult().makeEmptyAggregatedTestResult)());266 return;267 }268 if (globalConfig.onlyFailures) {269 if (failedTestsCache) {270 allTests = failedTestsCache.filterTests(allTests);271 } else {272 allTests = await sequencer.allFailedTests(allTests);273 }274 }275 const hasTests = allTests.length > 0;276 if (!hasTests) {277 const noTestsFoundMessage = (0, _getNoTestsFoundMessage.default)(278 testRunData,279 globalConfig280 );281 if (282 globalConfig.passWithNoTests ||283 globalConfig.findRelatedTests ||284 globalConfig.lastCommit ||285 globalConfig.onlyChanged286 ) {287 new (_console().CustomConsole)(outputStream, outputStream).log(288 noTestsFoundMessage289 );290 } else {291 new (_console().CustomConsole)(outputStream, outputStream).error(292 noTestsFoundMessage293 );294 (0, _exit().default)(1);295 }296 } else if (297 allTests.length === 1 &&298 globalConfig.silent !== true &&299 globalConfig.verbose !== false300 ) {301 const newConfig = {...globalConfig, verbose: true};302 globalConfig = Object.freeze(newConfig);303 }304 let collectHandles;305 if (globalConfig.detectOpenHandles) {306 collectHandles = (0, _collectHandles.default)();307 }308 if (hasTests) {309 await (0, _runGlobalHook.default)({310 allTests,311 globalConfig,312 moduleName: 'globalSetup'313 });314 }315 if (changedFilesPromise) {316 const changedFilesInfo = await changedFilesPromise;317 if (changedFilesInfo.changedFiles) {318 testSchedulerContext.changedFiles = changedFilesInfo.changedFiles;319 const sourcesRelatedToTestsInChangedFilesArray = (320 await Promise.all(321 contexts.map(async (_, index) => {322 const searchSource = searchSources[index];323 return searchSource.findRelatedSourcesFromTestsInChangedFiles(324 changedFilesInfo325 );326 })327 )328 ).reduce((total, paths) => total.concat(paths), []);329 testSchedulerContext.sourcesRelatedToTestsInChangedFiles = new Set(330 sourcesRelatedToTestsInChangedFilesArray331 );332 }333 }334 const scheduler = await (0, _TestScheduler.createTestScheduler)(335 globalConfig,336 {337 startRun338 },339 testSchedulerContext340 );341 const results = await scheduler.scheduleTests(allTests, testWatcher);342 await sequencer.cacheResults(allTests, results);343 if (hasTests) {344 await (0, _runGlobalHook.default)({345 allTests,346 globalConfig,347 moduleName: 'globalTeardown'348 });349 }350 await processResults(results, {351 collectHandles,352 json: globalConfig.json,353 onComplete,354 outputFile: globalConfig.outputFile,355 outputStream,356 testResultsProcessor: globalConfig.testResultsProcessor357 });...

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, 'ErrorWithStack', {6 enumerable: true,7 get: function () {8 return _ErrorWithStack.default;9 }10});11Object.defineProperty(exports, 'clearLine', {12 enumerable: true,13 get: function () {14 return _clearLine.default;15 }16});17Object.defineProperty(exports, 'convertDescriptorToString', {18 enumerable: true,19 get: function () {20 return _convertDescriptorToString.default;21 }22});23Object.defineProperty(exports, 'createDirectory', {24 enumerable: true,25 get: function () {26 return _createDirectory.default;27 }28});29Object.defineProperty(exports, 'deepCyclicCopy', {30 enumerable: true,31 get: function () {32 return _deepCyclicCopy.default;33 }34});35Object.defineProperty(exports, 'formatTime', {36 enumerable: true,37 get: function () {38 return _formatTime.default;39 }40});41Object.defineProperty(exports, 'globsToMatcher', {42 enumerable: true,43 get: function () {44 return _globsToMatcher.default;45 }46});47Object.defineProperty(exports, 'installCommonGlobals', {48 enumerable: true,49 get: function () {50 return _installCommonGlobals.default;51 }52});53Object.defineProperty(exports, 'interopRequireDefault', {54 enumerable: true,55 get: function () {56 return _interopRequireDefault.default;57 }58});59Object.defineProperty(exports, 'isInteractive', {60 enumerable: true,61 get: function () {62 return _isInteractive.default;63 }64});65Object.defineProperty(exports, 'isPromise', {66 enumerable: true,67 get: function () {68 return _isPromise.default;69 }70});71Object.defineProperty(exports, 'pluralize', {72 enumerable: true,73 get: function () {74 return _pluralize.default;75 }76});77exports.preRunMessage = void 0;78Object.defineProperty(exports, 'replacePathSepForGlob', {79 enumerable: true,80 get: function () {81 return _replacePathSepForGlob.default;82 }83});84Object.defineProperty(exports, 'requireOrImportModule', {85 enumerable: true,86 get: function () {87 return _requireOrImportModule.default;88 }89});90Object.defineProperty(exports, 'setGlobal', {91 enumerable: true,92 get: function () {93 return _setGlobal.default;94 }95});96exports.specialChars = void 0;97Object.defineProperty(exports, 'testPathPatternToRegExp', {98 enumerable: true,99 get: function () {100 return _testPathPatternToRegExp.default;101 }102});103Object.defineProperty(exports, 'tryRealpath', {104 enumerable: true,105 get: function () {106 return _tryRealpath.default;107 }108});109var _clearLine = _interopRequireDefault2(require('./clearLine'));110var _createDirectory = _interopRequireDefault2(require('./createDirectory'));111var _ErrorWithStack = _interopRequireDefault2(require('./ErrorWithStack'));112var _installCommonGlobals = _interopRequireDefault2(113 require('./installCommonGlobals')114);115var _interopRequireDefault = _interopRequireDefault2(116 require('./interopRequireDefault')117);118var _isInteractive = _interopRequireDefault2(require('./isInteractive'));119var _isPromise = _interopRequireDefault2(require('./isPromise'));120var _setGlobal = _interopRequireDefault2(require('./setGlobal'));121var _deepCyclicCopy = _interopRequireDefault2(require('./deepCyclicCopy'));122var _convertDescriptorToString = _interopRequireDefault2(123 require('./convertDescriptorToString')124);125var _specialChars = _interopRequireWildcard(require('./specialChars'));126exports.specialChars = _specialChars;127var _replacePathSepForGlob = _interopRequireDefault2(128 require('./replacePathSepForGlob')129);130var _testPathPatternToRegExp = _interopRequireDefault2(131 require('./testPathPatternToRegExp')132);133var _globsToMatcher = _interopRequireDefault2(require('./globsToMatcher'));134var _preRunMessage = _interopRequireWildcard(require('./preRunMessage'));135exports.preRunMessage = _preRunMessage;136var _pluralize = _interopRequireDefault2(require('./pluralize'));137var _formatTime = _interopRequireDefault2(require('./formatTime'));138var _tryRealpath = _interopRequireDefault2(require('./tryRealpath'));139var _requireOrImportModule = _interopRequireDefault2(140 require('./requireOrImportModule')141);142function _getRequireWildcardCache(nodeInterop) {143 if (typeof WeakMap !== 'function') return null;144 var cacheBabelInterop = new WeakMap();145 var cacheNodeInterop = new WeakMap();146 return (_getRequireWildcardCache = function (nodeInterop) {147 return nodeInterop ? cacheNodeInterop : cacheBabelInterop;148 })(nodeInterop);149}150function _interopRequireWildcard(obj, nodeInterop) {151 if (!nodeInterop && obj && obj.__esModule) {152 return obj;153 }154 if (obj === null || (typeof obj !== 'object' && typeof obj !== 'function')) {155 return {default: obj};156 }157 var cache = _getRequireWildcardCache(nodeInterop);158 if (cache && cache.has(obj)) {159 return cache.get(obj);160 }161 var newObj = {};162 var hasPropertyDescriptor =163 Object.defineProperty && Object.getOwnPropertyDescriptor;164 for (var key in obj) {165 if (key !== 'default' && Object.prototype.hasOwnProperty.call(obj, key)) {166 var desc = hasPropertyDescriptor167 ? Object.getOwnPropertyDescriptor(obj, key)168 : null;169 if (desc && (desc.get || desc.set)) {170 Object.defineProperty(newObj, key, desc);171 } else {172 newObj[key] = obj[key];173 }174 }175 }176 newObj.default = obj;177 if (cache) {178 cache.set(obj, newObj);179 }180 return newObj;181}182function _interopRequireDefault2(obj) {183 return obj && obj.__esModule ? obj : {default: obj};...

Full Screen

Full Screen

Project.js

Source:Project.js Github

copy

Full Screen

1import { writeMergePackageJson } from '@dbux/cli/lib/package-util';2import Project from '../../projectLib/Project';3import { buildJestRunBugCommand } from '../../util/jestUtil';4/** @typedef {import('../../projectLib/ExerciseConfig').ExerciseConfig} ExerciseConfig */5export default class JavascriptAlgorithmProject extends Project {6 gitRemote = 'trekhleb/javascript-algorithms.git';7 gitCommit = '9bb60fa';8 rmFiles = [9 'package-lock.json',10 '.babelrc', // we need babel.config.js instead11 '.husky' // unwanted commit hooks12 ];13 runCfg = {14 };15 async beforeInstall() {16 // remove husky from package.json17 writeMergePackageJson(this.projectPath, { scripts: { prepare: '' } });18 }19 canRunExercise(config) {20 return !!config.testFilePaths;21 }22 decorateExercise(config) {23 return {24 // id: i + 1,25 // name: config.testName,26 // description: bug.testName,27 runArgs: [28 '--runInBand', // -i29 '-t',30 /**31 * @see https://jestjs.io/docs/cli#--testnamepatternregex32 */33 `"${config.testNamePattern}"`,34 '--runTestsByPath',35 config.testFilePaths.join(' ')36 ],37 enableSourceMaps: false,38 ...config,39 // testFilePaths: bug.testFilePaths.map(p => `./${p}`)40 };41 }42 async selectExercise(exercise) {43 // nothing to do here44 }45 async runCommand(bug, cfg) {46 const { projectPath } = this;47 // const bugArgs = this.getMochaRunArgs(bug);48 const testCfg = this.getJestCfg(bug, [49 '--setupFilesAfterEnv ./dbuxJestSetup.js',50 '--colors'51 ]);52 /**53 * TODO: find `describe`54 * 55 * * for now, we cannot find the definition of the `describe` function56 * * or maybe some other way to determine how tests are registered and sorted?57 * * -> it's coming from `@jest/core` -> `runWithoutWatch`58 * * -> `nonFlagArgs` contains the test files (from `jest.config.js`)59 * * -> have not found the actual tests yet.60 * * -> for that, maybe console log tracing will help?61 * * if `jasmine` enabled -> https://github.com/facebook/jest/blob/e0b33b74b5afd738edc183858b5c34053cfc26dd/packages/jest-jasmine2/src/jasmine/Env.ts#L38362 */63 cfg = {64 ...cfg,65 ...testCfg,66 cwd: projectPath,67 /**68 * NOTE: Jest has a two-layer approach, where the first layer bootstraps Jest,69 * and the second layer runs inside a VM (after running through `@jest/transform` and more).70 * We found that, if we run `Jest` with `@babel/register`, 71 * Jest's own transformer doubles up the instrumentation on some of the code.72 * 73 * One possible solution: make sure, each library (or specific files) only runs in one of the layers, so74 * transformation never doubles up.75 *76 * Libraries that might be exclusively used in test layer:77 * * jest-runner78 * * jest-environment-node79 * Libraries that run code in both layers:80 * * jest-circus81 */82 // dbuxJs: null,83 dbuxArgs: [84 cfg.dbuxArgs,85 '--pw=jest[-]circus,jest[-]runner,jest[-]runtime,jest[-]environment[-]node,jest[-]jasmine2', //,@jest/core',86 // /**87 // * babel, debug, pirates, resolve, import, jest-resolve, jest-runtime, @jest/transform, regenerator-transform, source-map*: very likely to mess things up.88 // * human-signals, jest-haste-map, safe-buffer: caused weird problems?89 // * gensync: seems to be connected to regenerator-transform?90 // * graceful-fs: messy polyfilles91 // * 92 // * Uninteresting libraries:93 // * browserslist, react-is94 // * jsesc: data conversion95 // */96 // // eslint-disable-next-line max-len97 // '--pb=babel[-].*,graceful[-]fs,require.*,resolve.*,import.*,locate.*,pretty[-]format,jest[-]config,jest[-]validate,jest[-]resolve.*,jest[-]runtime,@jest/transform,regenerator[-]transform,.*source[-]map,browserslist,human[-]signals,react[-]is,jest[-]haste[-]map,@jest/reporters,debug,pirates,jsesc,gensync,safe-buffer',98 // '--fw=.*',99 // '--fb=requireOrImportModule\\.js',100 // // '--runtime="{\\"tracesDisabled\\":1}"'101 ].join(' ')102 };103 /**104 * NOTES105 * 106 * 1. node_modules/jest-util/build/index.js:38 getter might cause infinite loop (but does not for now)107 */108 return buildJestRunBugCommand(cfg);109 }...

Full Screen

Full Screen

requireOrImportModule.js

Source:requireOrImportModule.js Github

copy

Full Screen

...28 *29 * This source code is licensed under the MIT license found in the30 * LICENSE file in the root directory of this source tree.31 */32async function requireOrImportModule(33 filePath,34 applyInteropRequireDefault = true35) {36 if (!(0, _path().isAbsolute)(filePath) && filePath[0] === '.') {37 throw new Error(38 `Jest: requireOrImportModule path must be absolute, was "${filePath}"`39 );40 }41 try {42 const requiredModule = require(filePath);43 if (!applyInteropRequireDefault) {44 return requiredModule;45 }46 return (0, _interopRequireDefault.default)(requiredModule).default;...

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