Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore: Migrate bable-plugin-jest-hoist to Typescript #7898

Merged
merged 11 commits into from
Feb 16, 2019
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
205 changes: 205 additions & 0 deletions packages/babel-plugin-jest-hoist/build/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,205 @@
'use strict';

Object.defineProperty(exports, '__esModule', {
value: true
});
exports.default = void 0;

/**
* Copyright (c) Facebook, Inc. and its affiliates. 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.
*
* @flow
*/
const invariant = (condition, message) => {
if (!condition) {
throw new Error('babel-plugin-jest-hoist: ' + message);
}
}; // We allow `jest`, `expect`, `require`, all default Node.js globals and all
// ES2015 built-ins to be used inside of a `jest.mock` factory.
// We also allow variables prefixed with `mock` as an escape-hatch.

const WHITELISTED_IDENTIFIERS = {
Array: true,
ArrayBuffer: true,
Boolean: true,
DataView: true,
Date: true,
Error: true,
EvalError: true,
Float32Array: true,
Float64Array: true,
Function: true,
Generator: true,
GeneratorFunction: true,
Infinity: true,
Int16Array: true,
Int32Array: true,
Int8Array: true,
InternalError: true,
Intl: true,
JSON: true,
Map: true,
Math: true,
NaN: true,
Number: true,
Object: true,
Promise: true,
Proxy: true,
RangeError: true,
ReferenceError: true,
Reflect: true,
RegExp: true,
Set: true,
String: true,
Symbol: true,
SyntaxError: true,
TypeError: true,
URIError: true,
Uint16Array: true,
Uint32Array: true,
Uint8Array: true,
Uint8ClampedArray: true,
WeakMap: true,
WeakSet: true,
arguments: true,
console: true,
expect: true,
isNaN: true,
jest: true,
parseFloat: true,
parseInt: true,
require: true,
undefined: true
};
Object.keys(global).forEach(name => (WHITELISTED_IDENTIFIERS[name] = true));
const JEST_GLOBAL = {
name: 'jest'
};
const IDVisitor = {
ReferencedIdentifier(path) {
this.ids.add(path);
},

blacklist: ['TypeAnnotation', 'TSTypeAnnotation', 'TSTypeReference'],
ids: new Set()
};
const FUNCTIONS = Object.create(null);

FUNCTIONS.mock = args => {
if (args.length === 1) {
return args[0].isStringLiteral() || args[0].isLiteral();
} else if (args.length === 2 || args.length === 3) {
const moduleFactory = args[1];
invariant(
moduleFactory.isFunction(),
'The second argument of `jest.mock` must be an inline function.'
);
const ids = new Set();
const parentScope = moduleFactory.parentPath.scope;
moduleFactory.traverse(IDVisitor, {
ids
});
var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = undefined;

try {
for (
var _iterator = ids[Symbol.iterator](), _step;
!(_iteratorNormalCompletion = (_step = _iterator.next()).done);
_iteratorNormalCompletion = true
) {
const id = _step.value;
const name = id.node.name;
let found = false;
let scope = id.scope;

while (scope !== parentScope) {
if (scope.bindings[name]) {
found = true;
break;
}

scope = scope.parent;
}

if (!found) {
invariant(
(scope.hasGlobal(name) && WHITELISTED_IDENTIFIERS[name]) ||
/^mock/i.test(name) || // Allow istanbul's coverage variable to pass.
/^(?:__)?cov/.test(name),
'The module factory of `jest.mock()` is not allowed to ' +
'reference any out-of-scope variables.\n' +
'Invalid variable access: ' +
name +
'\n' +
'Whitelisted objects: ' +
Object.keys(WHITELISTED_IDENTIFIERS).join(', ') +
'.\n' +
'Note: This is a precaution to guard against uninitialized mock ' +
'variables. If it is ensured that the mock is required lazily, ' +
'variable names prefixed with `mock` (case insensitive) are permitted.'
);
}
}
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally {
try {
if (!_iteratorNormalCompletion && _iterator.return != null) {
_iterator.return();
}
} finally {
if (_didIteratorError) {
throw _iteratorError;
}
}
}

return true;
}

return false;
};

FUNCTIONS.unmock = args => args.length === 1 && args[0].isStringLiteral();

FUNCTIONS.deepUnmock = args => args.length === 1 && args[0].isStringLiteral();

FUNCTIONS.disableAutomock = FUNCTIONS.enableAutomock = args =>
args.length === 0;

var _default = () => {
const shouldHoistExpression = expr => {
if (!expr.isCallExpression()) {
return false;
}

const callee = expr.get('callee');
const object = callee.get('object');
const property = callee.get('property');
return (
property.isIdentifier() &&
FUNCTIONS[property.node.name] &&
(object.isIdentifier(JEST_GLOBAL) ||
(callee.isMemberExpression() && shouldHoistExpression(object))) &&
FUNCTIONS[property.node.name](expr.get('arguments'))
);
};

return {
visitor: {
ExpressionStatement(path) {
if (shouldHoistExpression(path.get('expression'))) {
path.node._blockHoist = Infinity;
}
}
}
};
};

exports.default = _default;
1 change: 1 addition & 0 deletions packages/babel-plugin-jest-hoist/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,5 +11,6 @@
},
"license": "MIT",
"main": "build/index.js",
"types": "build/index.d.ts",
"gitHead": "b16789230fd45056a7f2fa199bae06c7a1780deb"
}
Original file line number Diff line number Diff line change
Expand Up @@ -7,16 +7,16 @@
* @flow
SimenB marked this conversation as resolved.
Show resolved Hide resolved
*/

function invariant(condition, message) {
const invariant = (condition: any, message: any) => {
SimenB marked this conversation as resolved.
Show resolved Hide resolved
if (!condition) {
throw new Error('babel-plugin-jest-hoist: ' + message);
}
}
};

// We allow `jest`, `expect`, `require`, all default Node.js globals and all
// ES2015 built-ins to be used inside of a `jest.mock` factory.
// We also allow variables prefixed with `mock` as an escape-hatch.
const WHITELISTED_IDENTIFIERS = {
const WHITELISTED_IDENTIFIERS: {[key: string]: boolean} = {
Array: true,
ArrayBuffer: true,
Boolean: true,
Expand Down Expand Up @@ -73,14 +73,15 @@ Object.keys(global).forEach(name => (WHITELISTED_IDENTIFIERS[name] = true));

const JEST_GLOBAL = {name: 'jest'};
const IDVisitor = {
ReferencedIdentifier(path) {
ReferencedIdentifier(path: any) {
this.ids.add(path);
},
blacklist: ['TypeAnnotation', 'TSTypeAnnotation', 'TSTypeReference'],
ids: new Set(),
SimenB marked this conversation as resolved.
Show resolved Hide resolved
};

const FUNCTIONS: Object = Object.create(null);
FUNCTIONS.mock = args => {
const FUNCTIONS: {[key: string]: any} = Object.create(null);
FUNCTIONS.mock = (args: any) => {
if (args.length === 1) {
return args[0].isStringLiteral() || args[0].isLiteral();
} else if (args.length === 2 || args.length === 3) {
Expand Down Expand Up @@ -133,14 +134,16 @@ FUNCTIONS.mock = args => {
return false;
};

FUNCTIONS.unmock = args => args.length === 1 && args[0].isStringLiteral();
FUNCTIONS.deepUnmock = args => args.length === 1 && args[0].isStringLiteral();
FUNCTIONS.unmock = (args: Array<any>) =>
args.length === 1 && args[0].isStringLiteral();
FUNCTIONS.deepUnmock = (args: Array<any>) =>
args.length === 1 && args[0].isStringLiteral();

FUNCTIONS.disableAutomock = FUNCTIONS.enableAutomock = args =>
FUNCTIONS.disableAutomock = FUNCTIONS.enableAutomock = (args: any) =>
args.length === 0;

module.exports = () => {
const shouldHoistExpression = expr => {
export default () => {
SimenB marked this conversation as resolved.
Show resolved Hide resolved
const shouldHoistExpression = (expr: any): boolean => {
if (!expr.isCallExpression()) {
return false;
}
Expand Down
7 changes: 7 additions & 0 deletions packages/babel-plugin-jest-hoist/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"extends": "../../tsconfig.json",
"compilerOptions": {
"rootDir": "src",
"outDir": "build"
}
}