initial commit taken from gitlab.lrz.de

This commit is contained in:
privatereese
2018-08-24 18:09:42 +02:00
parent ae54ed4c48
commit fc05486403
28494 changed files with 2159823 additions and 0 deletions

42
node_modules/jest-runtime/build/cli/args.js generated vendored Normal file
View File

@@ -0,0 +1,42 @@
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
/**
* Copyright (c) 2014-present, Facebook, Inc. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*
*/
const usage = exports.usage = 'Usage: $0 [--config=<pathToConfigFile>] <file>';
const options = exports.options = {
cache: {
default: true,
description: 'Whether to use the preprocessor cache. Disable ' + 'the cache using --no-cache.',
type: 'boolean'
},
config: {
alias: 'c',
description: 'The path to a Jest config file.',
type: 'string'
},
debug: {
description: 'Print debugging info about your jest config.',
type: 'boolean'
},
version: {
alias: 'v',
description: 'Print the version and exit',
type: 'boolean'
},
watchman: {
default: true,
description: 'Whether to use watchman for file crawling. Disable using ' + '--no-watchman.',
type: 'boolean'
}
};

138
node_modules/jest-runtime/build/cli/index.js generated vendored Normal file
View File

@@ -0,0 +1,138 @@
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.run = run;
var _chalk;
function _load_chalk() {
return _chalk = _interopRequireDefault(require('chalk'));
}
var _os;
function _load_os() {
return _os = _interopRequireDefault(require('os'));
}
var _path;
function _load_path() {
return _path = _interopRequireDefault(require('path'));
}
var _yargs;
function _load_yargs() {
return _yargs = _interopRequireDefault(require('yargs'));
}
var _jestUtil;
function _load_jestUtil() {
return _jestUtil = require('jest-util');
}
var _jestValidate;
function _load_jestValidate() {
return _jestValidate = require('jest-validate');
}
var _jestConfig;
function _load_jestConfig() {
return _jestConfig = require('jest-config');
}
var _;
function _load_() {
return _ = _interopRequireDefault(require('../'));
}
var _args;
function _load_args() {
return _args = _interopRequireWildcard(require('./args'));
}
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
// eslint-disable-next-line import/default
const VERSION = require('../../package.json').version; /**
* Copyright (c) 2014-present, Facebook, Inc. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*
*/
function run(cliArgv, cliInfo) {
const realFs = require('fs');
const fs = require('graceful-fs');
fs.gracefulify(realFs);
let argv;
if (cliArgv) {
argv = cliArgv;
} else {
argv = (_yargs || _load_yargs()).default.usage((_args || _load_args()).usage).help(false).version(false).options((_args || _load_args()).options).argv;
(0, (_jestValidate || _load_jestValidate()).validateCLIOptions)(argv, (_args || _load_args()).options);
}
if (argv.help) {
(_yargs || _load_yargs()).default.showHelp();
process.on('exit', () => process.exitCode = 1);
return;
}
if (argv.version) {
console.log(`v${VERSION}\n`);
return;
}
if (!argv._.length) {
console.log('Please provide a path to a script. (See --help for details)');
process.on('exit', () => process.exitCode = 1);
return;
}
const root = process.cwd();
const filePath = (_path || _load_path()).default.resolve(root, argv._[0]);
if (argv.debug) {
const info = cliInfo ? ', ' + cliInfo.join(', ') : '';
console.log(`Using Jest Runtime v${VERSION}${info}`);
}
const options = (0, (_jestConfig || _load_jestConfig()).readConfig)(argv, root);
const globalConfig = options.globalConfig;
// Always disable automocking in scripts.
const config = Object.assign({}, options.projectConfig, {
automock: false,
unmockedModulePathPatterns: null
});
(_ || _load_()).default.createContext(config, {
maxWorkers: (_os || _load_os()).default.cpus().length - 1,
watchman: globalConfig.watchman
}).then(hasteMap => {
/* $FlowFixMe */
const Environment = require(config.testEnvironment);
const environment = new Environment(config);
(0, (_jestUtil || _load_jestUtil()).setGlobal)(environment.global, 'console', new (_jestUtil || _load_jestUtil()).Console(process.stdout, process.stderr));
environment.global.jestProjectConfig = config;
environment.global.jestGlobalConfig = globalConfig;
const runtime = new (_ || _load_()).default(config, environment, hasteMap.resolver);
runtime.requireModule(filePath);
}).catch(e => {
console.error((_chalk || _load_chalk()).default.red(e.stack || e));
process.on('exit', () => process.exitCode = 1);
});
}

681
node_modules/jest-runtime/build/index.js generated vendored Normal file
View File

@@ -0,0 +1,681 @@
'use strict';
var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }(); /**
* Copyright (c) 2014-present, Facebook, Inc. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*
*/
var _path;
function _load_path() {
return _path = _interopRequireDefault(require('path'));
}
var _jestHasteMap;
function _load_jestHasteMap() {
return _jestHasteMap = _interopRequireDefault(require('jest-haste-map'));
}
var _jestResolve;
function _load_jestResolve() {
return _jestResolve = _interopRequireDefault(require('jest-resolve'));
}
var _jestUtil;
function _load_jestUtil() {
return _jestUtil = require('jest-util');
}
var _jestRegexUtil;
function _load_jestRegexUtil() {
return _jestRegexUtil = require('jest-regex-util');
}
var _gracefulFs;
function _load_gracefulFs() {
return _gracefulFs = _interopRequireDefault(require('graceful-fs'));
}
var _stripBom;
function _load_stripBom() {
return _stripBom = _interopRequireDefault(require('strip-bom'));
}
var _script_transformer;
function _load_script_transformer() {
return _script_transformer = _interopRequireDefault(require('./script_transformer'));
}
var _should_instrument;
function _load_should_instrument() {
return _should_instrument = _interopRequireDefault(require('./should_instrument'));
}
var _cli;
function _load_cli() {
return _cli = require('./cli');
}
var _args;
function _load_args() {
return _args = require('./cli/args');
}
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
const NODE_MODULES = (_path || _load_path()).default.sep + 'node_modules' + (_path || _load_path()).default.sep;
const SNAPSHOT_EXTENSION = 'snap';
const getModuleNameMapper = config => {
if (Array.isArray(config.moduleNameMapper) && config.moduleNameMapper.length) {
return config.moduleNameMapper.map((_ref) => {
var _ref2 = _slicedToArray(_ref, 2);
let regex = _ref2[0],
moduleName = _ref2[1];
return { moduleName, regex: new RegExp(regex) };
});
}
return null;
};
const unmockRegExpCache = new WeakMap();
class Runtime {
constructor(config, environment, resolver, cacheFS, coverageOptions) {
this._cacheFS = cacheFS || Object.create(null);
this._config = config;
this._coverageOptions = coverageOptions || {
collectCoverage: false,
collectCoverageFrom: [],
collectCoverageOnlyFrom: null
};
this._currentlyExecutingModulePath = '';
this._environment = environment;
this._explicitShouldMock = Object.create(null);
this._internalModuleRegistry = Object.create(null);
this._isCurrentlyExecutingManualMock = null;
this._mockFactories = Object.create(null);
this._mockRegistry = Object.create(null);
this._moduleMocker = this._environment.moduleMocker;
this._moduleRegistry = Object.create(null);
this._needsCoverageMapped = new Set();
this._resolver = resolver;
this._scriptTransformer = new (_script_transformer || _load_script_transformer()).default(config);
this._shouldAutoMock = config.automock;
this._sourceMapRegistry = Object.create(null);
this._virtualMocks = Object.create(null);
this._mockMetaDataCache = Object.create(null);
this._shouldMockModuleCache = Object.create(null);
this._shouldUnmockTransitiveDependenciesCache = Object.create(null);
this._transitiveShouldMock = Object.create(null);
this._unmockList = unmockRegExpCache.get(config);
if (!this._unmockList && config.unmockedModulePathPatterns) {
this._unmockList = new RegExp(config.unmockedModulePathPatterns.join('|'));
unmockRegExpCache.set(config, this._unmockList);
}
if (config.automock) {
config.setupFiles.forEach(filePath => {
if (filePath && filePath.includes(NODE_MODULES)) {
const moduleID = this._resolver.getModuleID(this._virtualMocks, filePath);
this._transitiveShouldMock[moduleID] = false;
}
});
}
this.resetModules();
if (config.setupFiles.length) {
for (let i = 0; i < config.setupFiles.length; i++) {
this.requireModule(config.setupFiles[i]);
}
}
}
static shouldInstrument(filename, options, config) {
return (0, (_should_instrument || _load_should_instrument()).default)(filename, {
collectCoverage: options.collectCoverage,
collectCoverageFrom: options.collectCoverageFrom,
collectCoverageOnlyFrom: options.collectCoverageOnlyFrom
}, config);
}
static createContext(config, options) {
(0, (_jestUtil || _load_jestUtil()).createDirectory)(config.cacheDirectory);
const instance = Runtime.createHasteMap(config, {
console: options.console,
maxWorkers: options.maxWorkers,
resetCache: !config.cache,
watch: options.watch,
watchman: options.watchman
});
return instance.build().then(hasteMap => ({
config,
hasteFS: hasteMap.hasteFS,
moduleMap: hasteMap.moduleMap,
resolver: Runtime.createResolver(config, hasteMap.moduleMap)
}), error => {
throw error;
});
}
static createHasteMap(config, options) {
const ignorePattern = new RegExp([config.cacheDirectory].concat(config.modulePathIgnorePatterns).join('|'));
return new (_jestHasteMap || _load_jestHasteMap()).default({
cacheDirectory: config.cacheDirectory,
console: options && options.console,
extensions: [SNAPSHOT_EXTENSION].concat(config.moduleFileExtensions),
hasteImplModulePath: config.haste.hasteImplModulePath,
ignorePattern,
maxWorkers: options && options.maxWorkers || 1,
mocksPattern: (0, (_jestRegexUtil || _load_jestRegexUtil()).escapePathForRegex)((_path || _load_path()).default.sep + '__mocks__' + (_path || _load_path()).default.sep),
name: config.name,
platforms: config.haste.platforms || ['ios', 'android'],
providesModuleNodeModules: config.haste.providesModuleNodeModules,
resetCache: options && options.resetCache,
retainAllFiles: false,
roots: config.roots,
useWatchman: options && options.watchman,
watch: options && options.watch
});
}
static createResolver(config, moduleMap) {
return new (_jestResolve || _load_jestResolve()).default(moduleMap, {
browser: config.browser,
defaultPlatform: config.haste.defaultPlatform,
extensions: config.moduleFileExtensions.map(extension => '.' + extension),
hasCoreModules: true,
moduleDirectories: config.moduleDirectories,
moduleNameMapper: getModuleNameMapper(config),
modulePaths: config.modulePaths,
platforms: config.haste.platforms,
resolver: config.resolver,
rootDir: config.rootDir
});
}
static runCLI(args, info) {
return (0, (_cli || _load_cli()).run)(args, info);
}
static getCLIOptions() {
return (_args || _load_args()).options;
}
requireModule(from, moduleName, options) {
const moduleID = this._resolver.getModuleID(this._virtualMocks, from, moduleName);
let modulePath;
const moduleRegistry = !options || !options.isInternalModule ? this._moduleRegistry : this._internalModuleRegistry;
// Some old tests rely on this mocking behavior. Ideally we'll change this
// to be more explicit.
const moduleResource = moduleName && this._resolver.getModule(moduleName);
const manualMock = moduleName && this._resolver.getMockModule(from, moduleName);
if ((!options || !options.isInternalModule) && !moduleResource && manualMock && manualMock !== this._isCurrentlyExecutingManualMock && this._explicitShouldMock[moduleID] !== false) {
modulePath = manualMock;
}
if (moduleName && this._resolver.isCoreModule(moduleName)) {
return this._requireCoreModule(moduleName);
}
if (!modulePath) {
modulePath = this._resolveModule(from, moduleName);
}
if (!moduleRegistry[modulePath]) {
// We must register the pre-allocated module object first so that any
// circular dependencies that may arise while evaluating the module can
const localModule = {
children: [],
exports: {},
filename: modulePath,
id: modulePath,
loaded: false
};
moduleRegistry[modulePath] = localModule;
if ((_path || _load_path()).default.extname(modulePath) === '.json') {
localModule.exports = this._environment.global.JSON.parse((0, (_stripBom || _load_stripBom()).default)((_gracefulFs || _load_gracefulFs()).default.readFileSync(modulePath, 'utf8')));
} else if ((_path || _load_path()).default.extname(modulePath) === '.node') {
// $FlowFixMe
localModule.exports = require(modulePath);
} else {
this._execModule(localModule, options, moduleRegistry, from);
}
localModule.loaded = true;
}
return moduleRegistry[modulePath].exports;
}
requireInternalModule(from, to) {
return this.requireModule(from, to, { isInternalModule: true });
}
requireMock(from, moduleName) {
const moduleID = this._resolver.getModuleID(this._virtualMocks, from, moduleName);
if (this._mockRegistry[moduleID]) {
return this._mockRegistry[moduleID];
}
if (moduleID in this._mockFactories) {
return this._mockRegistry[moduleID] = this._mockFactories[moduleID]();
}
let manualMock = this._resolver.getMockModule(from, moduleName);
let modulePath;
if (manualMock) {
modulePath = this._resolveModule(from, manualMock);
} else {
modulePath = this._resolveModule(from, moduleName);
}
// If the actual module file has a __mocks__ dir sitting immediately next
// to it, look to see if there is a manual mock for this file.
//
// subDir1/my_module.js
// subDir1/__mocks__/my_module.js
// subDir2/my_module.js
// subDir2/__mocks__/my_module.js
//
// Where some other module does a relative require into each of the
// respective subDir{1,2} directories and expects a manual mock
// corresponding to that particular my_module.js file.
const moduleDir = (_path || _load_path()).default.dirname(modulePath);
const moduleFileName = (_path || _load_path()).default.basename(modulePath);
const potentialManualMock = (_path || _load_path()).default.join(moduleDir, '__mocks__', moduleFileName);
if ((_gracefulFs || _load_gracefulFs()).default.existsSync(potentialManualMock)) {
manualMock = true;
modulePath = potentialManualMock;
}
if (manualMock) {
const localModule = {
children: [],
exports: {},
filename: modulePath,
id: modulePath,
loaded: false
};
this._execModule(localModule, undefined, this._mockRegistry, from);
this._mockRegistry[moduleID] = localModule.exports;
localModule.loaded = true;
} else {
// Look for a real module to generate an automock from
this._mockRegistry[moduleID] = this._generateMock(from, moduleName);
}
return this._mockRegistry[moduleID];
}
requireModuleOrMock(from, moduleName) {
if (this._shouldMock(from, moduleName)) {
return this.requireMock(from, moduleName);
} else {
return this.requireModule(from, moduleName);
}
}
resetModules() {
this._mockRegistry = Object.create(null);
this._moduleRegistry = Object.create(null);
if (this._environment && this._environment.global) {
const envGlobal = this._environment.global;
Object.keys(envGlobal).forEach(key => {
const globalMock = envGlobal[key];
if (typeof globalMock === 'object' && globalMock !== null || typeof globalMock === 'function') {
globalMock._isMockFunction && globalMock.mockClear();
}
});
if (envGlobal.mockClearTimers) {
envGlobal.mockClearTimers();
}
}
}
getAllCoverageInfoCopy() {
return (0, (_jestUtil || _load_jestUtil()).deepCyclicCopy)(this._environment.global.__coverage__);
}
getSourceMapInfo(coveredFiles) {
return Object.keys(this._sourceMapRegistry).reduce((result, sourcePath) => {
if (coveredFiles.has(sourcePath) && this._needsCoverageMapped.has(sourcePath) && (_gracefulFs || _load_gracefulFs()).default.existsSync(this._sourceMapRegistry[sourcePath])) {
result[sourcePath] = this._sourceMapRegistry[sourcePath];
}
return result;
}, {});
}
getSourceMaps() {
return this._sourceMapRegistry;
}
setMock(from, moduleName, mockFactory, options) {
if (options && options.virtual) {
const mockPath = this._resolver.getModulePath(from, moduleName);
this._virtualMocks[mockPath] = true;
}
const moduleID = this._resolver.getModuleID(this._virtualMocks, from, moduleName);
this._explicitShouldMock[moduleID] = true;
this._mockFactories[moduleID] = mockFactory;
}
restoreAllMocks() {
this._moduleMocker.restoreAllMocks();
}
resetAllMocks() {
this._moduleMocker.resetAllMocks();
}
clearAllMocks() {
this._moduleMocker.clearAllMocks();
}
_resolveModule(from, to) {
return to ? this._resolver.resolveModule(from, to) : from;
}
_execModule(localModule, options, moduleRegistry, from) {
// If the environment was disposed, prevent this module from being executed.
if (!this._environment.global) {
return;
}
const isInternalModule = !!(options && options.isInternalModule);
const filename = localModule.filename;
const lastExecutingModulePath = this._currentlyExecutingModulePath;
this._currentlyExecutingModulePath = filename;
const origCurrExecutingManualMock = this._isCurrentlyExecutingManualMock;
this._isCurrentlyExecutingManualMock = filename;
const dirname = (_path || _load_path()).default.dirname(filename);
localModule.children = [];
Object.defineProperty(localModule, 'parent',
// https://github.com/facebook/flow/issues/285#issuecomment-270810619
{
enumerable: true,
get() {
return moduleRegistry[from] || null;
}
});
localModule.paths = this._resolver.getModulePaths(dirname);
Object.defineProperty(localModule, 'require', {
value: this._createRequireImplementation(localModule, options)
});
const transformedFile = this._scriptTransformer.transform(filename, {
collectCoverage: this._coverageOptions.collectCoverage,
collectCoverageFrom: this._coverageOptions.collectCoverageFrom,
collectCoverageOnlyFrom: this._coverageOptions.collectCoverageOnlyFrom,
isInternalModule
}, this._cacheFS[filename]);
if (transformedFile.sourceMapPath) {
this._sourceMapRegistry[filename] = transformedFile.sourceMapPath;
if (transformedFile.mapCoverage) {
this._needsCoverageMapped.add(filename);
}
}
const wrapper = this._environment.runScript(transformedFile.script)[(_script_transformer || _load_script_transformer()).default.EVAL_RESULT_VARIABLE];
wrapper.call(localModule.exports, // module context
localModule, // module object
localModule.exports, // module exports
localModule.require, // require implementation
dirname, // __dirname
filename, // __filename
this._environment.global, // global object
this._createJestObjectFor(filename,
// $FlowFixMe
localModule.require) // jest object
);
this._isCurrentlyExecutingManualMock = origCurrExecutingManualMock;
this._currentlyExecutingModulePath = lastExecutingModulePath;
}
_requireCoreModule(moduleName) {
if (moduleName === 'process') {
return this._environment.global.process;
}
// $FlowFixMe
return require(moduleName);
}
_generateMock(from, moduleName) {
const modulePath = this._resolveModule(from, moduleName);
if (!(modulePath in this._mockMetaDataCache)) {
// This allows us to handle circular dependencies while generating an
// automock
this._mockMetaDataCache[modulePath] = this._moduleMocker.getMetadata({});
// In order to avoid it being possible for automocking to potentially
// cause side-effects within the module environment, we need to execute
// the module in isolation. This could cause issues if the module being
// mocked has calls into side-effectful APIs on another module.
const origMockRegistry = this._mockRegistry;
const origModuleRegistry = this._moduleRegistry;
this._mockRegistry = Object.create(null);
this._moduleRegistry = Object.create(null);
const moduleExports = this.requireModule(from, moduleName);
// Restore the "real" module/mock registries
this._mockRegistry = origMockRegistry;
this._moduleRegistry = origModuleRegistry;
const mockMetadata = this._moduleMocker.getMetadata(moduleExports);
if (mockMetadata == null) {
throw new Error(`Failed to get mock metadata: ${modulePath}\n\n` + `See: http://facebook.github.io/jest/docs/manual-mocks.html#content`);
}
this._mockMetaDataCache[modulePath] = mockMetadata;
}
return this._moduleMocker.generateFromMetadata(this._mockMetaDataCache[modulePath]);
}
_shouldMock(from, moduleName) {
const mockPath = this._resolver.getModulePath(from, moduleName);
if (mockPath in this._virtualMocks) {
return true;
}
const explicitShouldMock = this._explicitShouldMock;
const moduleID = this._resolver.getModuleID(this._virtualMocks, from, moduleName);
const key = from + (_path || _load_path()).default.delimiter + moduleID;
if (moduleID in explicitShouldMock) {
return explicitShouldMock[moduleID];
}
if (!this._shouldAutoMock || this._resolver.isCoreModule(moduleName) || this._shouldUnmockTransitiveDependenciesCache[key]) {
return false;
}
if (moduleID in this._shouldMockModuleCache) {
return this._shouldMockModuleCache[moduleID];
}
let modulePath;
try {
modulePath = this._resolveModule(from, moduleName);
} catch (e) {
const manualMock = this._resolver.getMockModule(from, moduleName);
if (manualMock) {
this._shouldMockModuleCache[moduleID] = true;
return true;
}
throw e;
}
if (this._unmockList && this._unmockList.test(modulePath)) {
this._shouldMockModuleCache[moduleID] = false;
return false;
}
// transitive unmocking for package managers that store flat packages (npm3)
const currentModuleID = this._resolver.getModuleID(this._virtualMocks, from);
if (this._transitiveShouldMock[currentModuleID] === false || from.includes(NODE_MODULES) && modulePath.includes(NODE_MODULES) && (this._unmockList && this._unmockList.test(from) || explicitShouldMock[currentModuleID] === false)) {
this._transitiveShouldMock[moduleID] = false;
this._shouldUnmockTransitiveDependenciesCache[key] = true;
return false;
}
return this._shouldMockModuleCache[moduleID] = true;
}
_createRequireImplementation(from, options) {
const moduleRequire = options && options.isInternalModule ? moduleName => this.requireInternalModule(from.filename, moduleName) : this.requireModuleOrMock.bind(this, from.filename);
moduleRequire.cache = Object.create(null);
moduleRequire.extensions = Object.create(null);
moduleRequire.requireActual = this.requireModule.bind(this, from.filename);
moduleRequire.requireMock = this.requireMock.bind(this, from.filename);
moduleRequire.resolve = moduleName => this._resolveModule(from.filename, moduleName);
Object.defineProperty(moduleRequire, 'main', {
enumerable: true,
get() {
let mainModule = from.parent;
while (mainModule && mainModule.parent && mainModule.id !== mainModule.parent.id) {
mainModule = mainModule.parent;
}
return mainModule;
}
});
return moduleRequire;
}
_createJestObjectFor(from, localRequire) {
const disableAutomock = () => {
this._shouldAutoMock = false;
return jestObject;
};
const enableAutomock = () => {
this._shouldAutoMock = true;
return jestObject;
};
const unmock = moduleName => {
const moduleID = this._resolver.getModuleID(this._virtualMocks, from, moduleName);
this._explicitShouldMock[moduleID] = false;
return jestObject;
};
const deepUnmock = moduleName => {
const moduleID = this._resolver.getModuleID(this._virtualMocks, from, moduleName);
this._explicitShouldMock[moduleID] = false;
this._transitiveShouldMock[moduleID] = false;
return jestObject;
};
const mock = (moduleName, mockFactory, options) => {
if (mockFactory !== undefined) {
return setMockFactory(moduleName, mockFactory, options);
}
const moduleID = this._resolver.getModuleID(this._virtualMocks, from, moduleName);
this._explicitShouldMock[moduleID] = true;
return jestObject;
};
const setMockFactory = (moduleName, mockFactory, options) => {
this.setMock(from, moduleName, mockFactory, options);
return jestObject;
};
const clearAllMocks = () => {
this.clearAllMocks();
return jestObject;
};
const resetAllMocks = () => {
this.resetAllMocks();
return jestObject;
};
const restoreAllMocks = () => {
this.restoreAllMocks();
return jestObject;
};
const useFakeTimers = () => {
this._environment.fakeTimers.useFakeTimers();
return jestObject;
};
const useRealTimers = () => {
this._environment.fakeTimers.useRealTimers();
return jestObject;
};
const resetModules = () => {
this.resetModules();
return jestObject;
};
const fn = this._moduleMocker.fn.bind(this._moduleMocker);
const spyOn = this._moduleMocker.spyOn.bind(this._moduleMocker);
const setTimeout = timeout => {
this._environment.global.jasmine ? this._environment.global.jasmine.DEFAULT_TIMEOUT_INTERVAL = timeout : this._environment.global[Symbol.for('TEST_TIMEOUT_SYMBOL')] = timeout;
return jestObject;
};
const jestObject = {
addMatchers: matchers => this._environment.global.jasmine.addMatchers(matchers),
advanceTimersByTime: msToRun => this._environment.fakeTimers.advanceTimersByTime(msToRun),
autoMockOff: disableAutomock,
autoMockOn: enableAutomock,
clearAllMocks,
clearAllTimers: () => this._environment.fakeTimers.clearAllTimers(),
deepUnmock,
disableAutomock,
doMock: mock,
dontMock: unmock,
enableAutomock,
fn,
genMockFn: fn,
genMockFromModule: moduleName => this._generateMock(from, moduleName),
genMockFunction: fn,
isMockFunction: this._moduleMocker.isMockFunction,
mock,
requireActual: localRequire.requireActual,
requireMock: localRequire.requireMock,
resetAllMocks,
resetModuleRegistry: resetModules,
resetModules,
restoreAllMocks,
runAllImmediates: () => this._environment.fakeTimers.runAllImmediates(),
runAllTicks: () => this._environment.fakeTimers.runAllTicks(),
runAllTimers: () => this._environment.fakeTimers.runAllTimers(),
runOnlyPendingTimers: () => this._environment.fakeTimers.runOnlyPendingTimers(),
runTimersToTime: msToRun => this._environment.fakeTimers.advanceTimersByTime(msToRun),
setMock: (moduleName, mock) => setMockFactory(moduleName, () => mock),
setTimeout,
spyOn,
unmock,
useFakeTimers,
useRealTimers
};
return jestObject;
}
}
Runtime.ScriptTransformer = (_script_transformer || _load_script_transformer()).default;
module.exports = Runtime;

477
node_modules/jest-runtime/build/script_transformer.js generated vendored Normal file
View File

@@ -0,0 +1,477 @@
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _crypto;
function _load_crypto() {
return _crypto = _interopRequireDefault(require('crypto'));
}
var _path;
function _load_path() {
return _path = _interopRequireDefault(require('path'));
}
var _vm;
function _load_vm() {
return _vm = _interopRequireDefault(require('vm'));
}
var _jestUtil;
function _load_jestUtil() {
return _jestUtil = require('jest-util');
}
var _gracefulFs;
function _load_gracefulFs() {
return _gracefulFs = _interopRequireDefault(require('graceful-fs'));
}
var _babelCore;
function _load_babelCore() {
return _babelCore = require('babel-core');
}
var _babelPluginIstanbul;
function _load_babelPluginIstanbul() {
return _babelPluginIstanbul = _interopRequireDefault(require('babel-plugin-istanbul'));
}
var _convertSourceMap;
function _load_convertSourceMap() {
return _convertSourceMap = _interopRequireDefault(require('convert-source-map'));
}
var _jestHasteMap;
function _load_jestHasteMap() {
return _jestHasteMap = _interopRequireDefault(require('jest-haste-map'));
}
var _jsonStableStringify;
function _load_jsonStableStringify() {
return _jsonStableStringify = _interopRequireDefault(require('json-stable-stringify'));
}
var _slash;
function _load_slash() {
return _slash = _interopRequireDefault(require('slash'));
}
var _package;
function _load_package() {
return _package = require('../package.json');
}
var _should_instrument;
function _load_should_instrument() {
return _should_instrument = _interopRequireDefault(require('./should_instrument'));
}
var _writeFileAtomic;
function _load_writeFileAtomic() {
return _writeFileAtomic = _interopRequireDefault(require('write-file-atomic'));
}
var _realpathNative;
function _load_realpathNative() {
return _realpathNative = require('realpath-native');
}
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
const cache = new Map(); /**
* Copyright (c) 2014-present, Facebook, Inc. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*
*/
const configToJsonMap = new Map();
// Cache regular expressions to test whether the file needs to be preprocessed
const ignoreCache = new WeakMap();
// To reset the cache for specific changesets (rather than package version).
const CACHE_VERSION = '1';
class ScriptTransformer {
constructor(config) {
this._config = config;
this._transformCache = new Map();
}
_getCacheKey(fileData, filename, instrument) {
if (!configToJsonMap.has(this._config)) {
// We only need this set of config options that can likely influence
// cached output instead of all config options.
configToJsonMap.set(this._config, (0, (_jsonStableStringify || _load_jsonStableStringify()).default)(this._config));
}
const configString = configToJsonMap.get(this._config) || '';
const transformer = this._getTransformer(filename);
if (transformer && typeof transformer.getCacheKey === 'function') {
return (_crypto || _load_crypto()).default.createHash('md5').update(transformer.getCacheKey(fileData, filename, configString, {
instrument,
rootDir: this._config.rootDir
})).update(CACHE_VERSION).digest('hex');
} else {
return (_crypto || _load_crypto()).default.createHash('md5').update(fileData).update(configString).update(instrument ? 'instrument' : '').update(CACHE_VERSION).digest('hex');
}
}
_getFileCachePath(filename, content, instrument) {
const baseCacheDir = (_jestHasteMap || _load_jestHasteMap()).default.getCacheFilePath(this._config.cacheDirectory, 'jest-transform-cache-' + this._config.name, (_package || _load_package()).version);
const cacheKey = this._getCacheKey(content, filename, instrument);
// Create sub folders based on the cacheKey to avoid creating one
// directory with many files.
const cacheDir = (_path || _load_path()).default.join(baseCacheDir, cacheKey[0] + cacheKey[1]);
const cachePath = (0, (_slash || _load_slash()).default)((_path || _load_path()).default.join(cacheDir, (_path || _load_path()).default.basename(filename, (_path || _load_path()).default.extname(filename)) + '_' + cacheKey));
(0, (_jestUtil || _load_jestUtil()).createDirectory)(cacheDir);
return cachePath;
}
_getTransformPath(filename) {
for (let i = 0; i < this._config.transform.length; i++) {
if (new RegExp(this._config.transform[i][0]).test(filename)) {
return this._config.transform[i][1];
}
}
return null;
}
_getTransformer(filename) {
let transform;
if (!this._config.transform || !this._config.transform.length) {
return null;
}
const transformPath = this._getTransformPath(filename);
if (transformPath) {
const transformer = this._transformCache.get(transformPath);
if (transformer != null) {
return transformer;
}
// $FlowFixMe
transform = require(transformPath);
if (typeof transform.process !== 'function') {
throw new TypeError('Jest: a transform must export a `process` function.');
}
if (typeof transform.createTransformer === 'function') {
transform = transform.createTransformer();
}
this._transformCache.set(transformPath, transform);
}
return transform;
}
_instrumentFile(filename, content) {
return (0, (_babelCore || _load_babelCore()).transform)(content, {
auxiliaryCommentBefore: ' istanbul ignore next ',
babelrc: false,
filename,
plugins: [[(_babelPluginIstanbul || _load_babelPluginIstanbul()).default, {
// files outside `cwd` will not be instrumented
cwd: this._config.rootDir,
exclude: [],
useInlineSourceMaps: false
}]],
retainLines: true
}).code;
}
_getRealPath(filepath) {
try {
return (0, (_realpathNative || _load_realpathNative()).sync)(filepath) || filepath;
} catch (err) {
return filepath;
}
}
transformSource(filepath, content, instrument) {
const filename = this._getRealPath(filepath);
const transform = this._getTransformer(filename);
const cacheFilePath = this._getFileCachePath(filename, content, instrument);
let sourceMapPath = cacheFilePath + '.map';
// Ignore cache if `config.cache` is set (--no-cache)
let code = this._config.cache ? readCodeCacheFile(cacheFilePath) : null;
const shouldCallTransform = transform && shouldTransform(filename, this._config);
// That means that the transform has a custom instrumentation
// logic and will handle it based on `config.collectCoverage` option
const transformWillInstrument = shouldCallTransform && transform && transform.canInstrument;
// If we handle the coverage instrumentation, we should try to map code
// coverage against original source with any provided source map
const mapCoverage = instrument && !transformWillInstrument;
if (code) {
// This is broken: we return the code, and a path for the source map
// directly from the cache. But, nothing ensures the source map actually
// matches that source code. They could have gotten out-of-sync in case
// two separate processes write concurrently to the same cache files.
return {
code,
mapCoverage,
sourceMapPath
};
}
let transformed = {
code: content,
map: null
};
if (transform && shouldCallTransform) {
const processed = transform.process(content, filename, this._config, {
instrument,
returnSourceString: false
});
if (typeof processed === 'string') {
transformed.code = processed;
} else if (processed != null && typeof processed.code === 'string') {
transformed = processed;
} else {
throw new TypeError("Jest: a transform's `process` function must return a string, " + 'or an object with `code` key containing this string.');
}
}
if (!transformed.map) {
//Could be a potential freeze here.
//See: https://github.com/facebook/jest/pull/5177#discussion_r158883570
const inlineSourceMap = (_convertSourceMap || _load_convertSourceMap()).default.fromSource(transformed.code);
if (inlineSourceMap) {
transformed.map = inlineSourceMap.toJSON();
}
}
if (!transformWillInstrument && instrument) {
code = this._instrumentFile(filename, transformed.code);
} else {
code = transformed.code;
}
if (transformed.map) {
const sourceMapContent = typeof transformed.map === 'string' ? transformed.map : JSON.stringify(transformed.map);
writeCacheFile(sourceMapPath, sourceMapContent);
} else {
sourceMapPath = null;
}
writeCodeCacheFile(cacheFilePath, code);
return {
code,
mapCoverage,
sourceMapPath
};
}
_transformAndBuildScript(filename, options, instrument, fileSource) {
const isInternalModule = !!(options && options.isInternalModule);
const isCoreModule = !!(options && options.isCoreModule);
const content = stripShebang(fileSource || (_gracefulFs || _load_gracefulFs()).default.readFileSync(filename, 'utf8'));
let wrappedCode;
let sourceMapPath = null;
let mapCoverage = false;
const willTransform = !isInternalModule && !isCoreModule && (shouldTransform(filename, this._config) || instrument);
try {
if (willTransform) {
const transformedSource = this.transformSource(filename, content, instrument);
wrappedCode = wrap(transformedSource.code);
sourceMapPath = transformedSource.sourceMapPath;
mapCoverage = transformedSource.mapCoverage;
} else {
wrappedCode = wrap(content);
}
return {
mapCoverage,
script: new (_vm || _load_vm()).default.Script(wrappedCode, {
displayErrors: true,
filename: isCoreModule ? 'jest-nodejs-core-' + filename : filename
}),
sourceMapPath
};
} catch (e) {
if (e.codeFrame) {
e.stack = e.codeFrame;
}
throw e;
}
}
transform(filename, options, fileSource) {
let scriptCacheKey = null;
let instrument = false;
let result = '';
if (!options.isCoreModule) {
instrument = (0, (_should_instrument || _load_should_instrument()).default)(filename, options, this._config);
scriptCacheKey = getScriptCacheKey(filename, this._config, instrument);
result = cache.get(scriptCacheKey);
}
if (result) {
return result;
}
result = this._transformAndBuildScript(filename, options, instrument, fileSource);
if (scriptCacheKey) {
cache.set(scriptCacheKey, result);
}
return result;
}
}
exports.default = ScriptTransformer;
const removeFile = path => {
try {
(_gracefulFs || _load_gracefulFs()).default.unlinkSync(path);
} catch (e) {}
};
const stripShebang = content => {
// If the file data starts with a shebang remove it. Leaves the empty line
// to keep stack trace line numbers correct.
if (content.startsWith('#!')) {
return content.replace(/^#!.*/, '');
} else {
return content;
}
};
/**
* This is like `writeCacheFile` but with an additional sanity checksum. We
* cannot use the same technique for source maps because we expose source map
* cache file paths directly to callsites, with the expectation they can read
* it right away. This is not a great system, because source map cache file
* could get corrupted, out-of-sync, etc.
*/
function writeCodeCacheFile(cachePath, code) {
const checksum = (_crypto || _load_crypto()).default.createHash('md5').update(code).digest('hex');
writeCacheFile(cachePath, checksum + '\n' + code);
}
/**
* Read counterpart of `writeCodeCacheFile`. We verify that the content of the
* file matches the checksum, in case some kind of corruption happened. This
* could happen if an older version of `jest-runtime` writes non-atomically to
* the same cache, for example.
*/
function readCodeCacheFile(cachePath) {
const content = readCacheFile(cachePath);
if (content == null) {
return null;
}
const code = content.substr(33);
const checksum = (_crypto || _load_crypto()).default.createHash('md5').update(code).digest('hex');
if (checksum === content.substr(0, 32)) {
return code;
}
return null;
}
/**
* Writing to the cache atomically relies on 'rename' being atomic on most
* file systems. Doing atomic write reduces the risk of corruption by avoiding
* two processes to write to the same file at the same time. It also reduces
* the risk of reading a file that's being overwritten at the same time.
*/
const writeCacheFile = (cachePath, fileData) => {
try {
(_writeFileAtomic || _load_writeFileAtomic()).default.sync(cachePath, fileData, { encoding: 'utf8' });
} catch (e) {
if (cacheWriteErrorSafeToIgnore(e, cachePath)) {
return;
}
e.message = 'jest: failed to cache transform results in: ' + cachePath + '\nFailure message: ' + e.message;
removeFile(cachePath);
throw e;
}
};
/**
* On Windows, renames are not atomic, leading to EPERM exceptions when two
* processes attempt to rename to the same target file at the same time.
* If the target file exists we can be reasonably sure another process has
* legitimately won a cache write race and ignore the error.
*/
const cacheWriteErrorSafeToIgnore = (e, cachePath) => {
return process.platform === 'win32' && e.code === 'EPERM' && (_gracefulFs || _load_gracefulFs()).default.existsSync(cachePath);
};
const readCacheFile = cachePath => {
if (!(_gracefulFs || _load_gracefulFs()).default.existsSync(cachePath)) {
return null;
}
let fileData;
try {
fileData = (_gracefulFs || _load_gracefulFs()).default.readFileSync(cachePath, 'utf8');
} catch (e) {
e.message = 'jest: failed to read cache file: ' + cachePath + '\nFailure message: ' + e.message;
removeFile(cachePath);
throw e;
}
if (fileData == null) {
// We must have somehow created the file but failed to write to it,
// let's delete it and retry.
removeFile(cachePath);
}
return fileData;
};
const getScriptCacheKey = (filename, config, instrument) => {
const mtime = (_gracefulFs || _load_gracefulFs()).default.statSync(filename).mtime;
return filename + '_' + mtime.getTime() + (instrument ? '_instrumented' : '');
};
const shouldTransform = (filename, config) => {
if (!ignoreCache.has(config)) {
if (!config.transformIgnorePatterns || config.transformIgnorePatterns.length === 0) {
ignoreCache.set(config, null);
} else {
ignoreCache.set(config, new RegExp(config.transformIgnorePatterns.join('|')));
}
}
const ignoreRegexp = ignoreCache.get(config);
const isIgnored = ignoreRegexp ? ignoreRegexp.test(filename) : false;
return !!config.transform && !!config.transform.length && !isIgnored;
};
const wrap = content => '({"' + ScriptTransformer.EVAL_RESULT_VARIABLE + '":function(module,exports,require,__dirname,__filename,global,jest){' + content + '\n}});';
ScriptTransformer.EVAL_RESULT_VARIABLE = 'Object.<anonymous>';

76
node_modules/jest-runtime/build/should_instrument.js generated vendored Normal file
View File

@@ -0,0 +1,76 @@
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = shouldInstrument;
var _path;
function _load_path() {
return _path = _interopRequireDefault(require('path'));
}
var _jestRegexUtil;
function _load_jestRegexUtil() {
return _jestRegexUtil = require('jest-regex-util');
}
var _micromatch;
function _load_micromatch() {
return _micromatch = _interopRequireDefault(require('micromatch'));
}
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
const MOCKS_PATTERN = new RegExp((0, (_jestRegexUtil || _load_jestRegexUtil()).escapePathForRegex)((_path || _load_path()).default.sep + '__mocks__' + (_path || _load_path()).default.sep)); /**
* Copyright (c) 2014-present, Facebook, Inc. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*
*/
function shouldInstrument(filename, options, config) {
if (!options.collectCoverage) {
return false;
}
if (config.forceCoverageMatch && config.forceCoverageMatch.length && (_micromatch || _load_micromatch()).default.any(filename, config.forceCoverageMatch)) {
return true;
}
if (config.testRegex && filename.match(config.testRegex)) {
return false;
}
if (config.testMatch && config.testMatch.length && (_micromatch || _load_micromatch()).default.any(filename, config.testMatch)) {
return false;
}
if (
// This configuration field contains an object in the form of:
// {'path/to/file.js': true}
options.collectCoverageOnlyFrom && !options.collectCoverageOnlyFrom[filename]) {
return false;
}
if (
// still cover if `only` is specified
!options.collectCoverageOnlyFrom && options.collectCoverageFrom && !(0, (_micromatch || _load_micromatch()).default)([(_path || _load_path()).default.relative(config.rootDir, filename)], options.collectCoverageFrom).length) {
return false;
}
if (config.coveragePathIgnorePatterns && config.coveragePathIgnorePatterns.some(pattern => filename.match(pattern))) {
return false;
}
if (MOCKS_PATTERN.test(filename)) {
return false;
}
return true;
}