-
-
Notifications
You must be signed in to change notification settings - Fork 6.5k
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
Changes from all commits
Commits
Show all changes
11 commits
Select commit
Hold shift + click to select a range
d1dfa86
after migration
deneuv34 60ab8be
finish migrate
deneuv34 38714da
fix some inline revision
deneuv34 143b4e2
Merge branch 'master' into ts-bable-plugin-jest-hoist
SimenB 04fa160
remove built output
SimenB fb73462
ignore instead of setting ids
SimenB a880059
add some type info
SimenB 7540cba
more types
SimenB 8048295
less any
SimenB e7de91a
Merge branch 'master' into ts-bable-plugin-jest-hoist
SimenB 61b6208
changelog
SimenB File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file was deleted.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,186 @@ | ||
/** | ||
* 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. | ||
* | ||
*/ | ||
|
||
// Only used for types | ||
// eslint-disable-next-line | ||
import {NodePath, Visitor} from '@babel/traverse'; | ||
// eslint-disable-next-line | ||
import {Identifier} from '@babel/types'; | ||
|
||
const invariant = (condition: unknown, message: string) => { | ||
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: Set<string> = new Set([ | ||
'Array', | ||
'ArrayBuffer', | ||
'Boolean', | ||
'DataView', | ||
'Date', | ||
'Error', | ||
'EvalError', | ||
'Float32Array', | ||
'Float64Array', | ||
'Function', | ||
'Generator', | ||
'GeneratorFunction', | ||
'Infinity', | ||
'Int16Array', | ||
'Int32Array', | ||
'Int8Array', | ||
'InternalError', | ||
'Intl', | ||
'JSON', | ||
'Map', | ||
'Math', | ||
'NaN', | ||
'Number', | ||
'Object', | ||
'Promise', | ||
'Proxy', | ||
'RangeError', | ||
'ReferenceError', | ||
'Reflect', | ||
'RegExp', | ||
'Set', | ||
'String', | ||
'Symbol', | ||
'SyntaxError', | ||
'TypeError', | ||
'URIError', | ||
'Uint16Array', | ||
'Uint32Array', | ||
'Uint8Array', | ||
'Uint8ClampedArray', | ||
'WeakMap', | ||
'WeakSet', | ||
'arguments', | ||
'console', | ||
'expect', | ||
'isNaN', | ||
'jest', | ||
'parseFloat', | ||
'parseInt', | ||
'require', | ||
'undefined', | ||
]); | ||
Object.keys(global).forEach(name => { | ||
WHITELISTED_IDENTIFIERS.add(name); | ||
}); | ||
|
||
const JEST_GLOBAL = {name: 'jest'}; | ||
// TODO: Should be Visitor<{ids: Set<NodePath<Identifier>>}>, but `ReferencedIdentifier` doesn't exist | ||
const IDVisitor = { | ||
ReferencedIdentifier(path: NodePath<Identifier>) { | ||
// @ts-ignore: passed as Visitor State | ||
this.ids.add(path); | ||
}, | ||
blacklist: ['TypeAnnotation', 'TSTypeAnnotation', 'TSTypeReference'], | ||
}; | ||
|
||
const FUNCTIONS: { | ||
[key: string]: (args: Array<NodePath>) => boolean; | ||
} = Object.create(null); | ||
|
||
FUNCTIONS.mock = (args: Array<NodePath>) => { | ||
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: Set<NodePath<Identifier>> = new Set(); | ||
const parentScope = moduleFactory.parentPath.scope; | ||
// @ts-ignore: Same as above: ReferencedIdentifier doesn't exist | ||
moduleFactory.traverse(IDVisitor, {ids}); | ||
for (const id of ids) { | ||
const {name} = id.node; | ||
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.has(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: ' + | ||
Array.from(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.', | ||
); | ||
} | ||
} | ||
|
||
return true; | ||
} | ||
return false; | ||
}; | ||
|
||
FUNCTIONS.unmock = (args: Array<NodePath>) => | ||
args.length === 1 && args[0].isStringLiteral(); | ||
FUNCTIONS.deepUnmock = (args: Array<NodePath>) => | ||
args.length === 1 && args[0].isStringLiteral(); | ||
FUNCTIONS.disableAutomock = FUNCTIONS.enableAutomock = ( | ||
args: Array<NodePath>, | ||
) => args.length === 0; | ||
|
||
export = () => { | ||
const shouldHoistExpression = (expr: NodePath): boolean => { | ||
if (!expr.isCallExpression()) { | ||
return false; | ||
} | ||
|
||
const callee = expr.get('callee'); | ||
// TODO: avoid type casts - the types can be arrays (is it possible to ignore that without casting?) | ||
const object = callee.get('object') as NodePath; | ||
const property = callee.get('property') as NodePath; | ||
return ( | ||
property.isIdentifier() && | ||
FUNCTIONS[property.node.name] && | ||
(object.isIdentifier(JEST_GLOBAL) || | ||
(callee.isMemberExpression() && shouldHoistExpression(object))) && | ||
FUNCTIONS[property.node.name](expr.get('arguments')) | ||
); | ||
}; | ||
|
||
const visitor: Visitor = { | ||
ExpressionStatement(path) { | ||
if (shouldHoistExpression(path.get('expression'))) { | ||
// @ts-ignore: private, magical property | ||
path.node._blockHoist = Infinity; | ||
} | ||
}, | ||
}; | ||
|
||
return {visitor}; | ||
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,7 @@ | ||
{ | ||
"extends": "../../tsconfig.json", | ||
"compilerOptions": { | ||
"rootDir": "src", | ||
"outDir": "build" | ||
} | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Why not install this type as a dev dependency?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
It's part of the public interface