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

fix(hoist-plugin): hoist pure constants to support experimental JSX transform in mocks #10723

Merged
merged 9 commits into from
Nov 1, 2020
Merged
Show file tree
Hide file tree
Changes from 4 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
5 changes: 4 additions & 1 deletion packages/babel-plugin-jest-hoist/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,12 @@
},
"devDependencies": {
"@babel/core": "^7.11.6",
"@babel/preset-react": "^7.12.1",
"@types/babel__template": "^7.0.2",
"@types/node": "*",
"babel-plugin-tester": "^10.0.0"
"@types/prettier": "^2.0.0",
"babel-plugin-tester": "^10.0.0",
"prettier": "^2.1.1"
},
"publishConfig": {
"access": "public"
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,46 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP

exports[`babel-plugin-jest-hoist automatic react runtime: automatic react runtime 1`] = `

jest.mock('./App', () => () => <div>Hello world</div>);

↓ ↓ ↓ ↓ ↓ ↓

_getJestObj().mock("./App", () => () =>
/*#__PURE__*/ _jsxDEV(
"div",
{
children: "Hello world"
},
void 0,
false,
{
fileName: _hoistedMockFactoryVariable(),
lineNumber: 1,
columnNumber: 32
},
this
)
);

import { jsxDEV as _jsxDEV } from "react/jsx-dev-runtime";
var _jsxFileName = "/root/project/src/file.js";

function _getJestObj() {
const { jest } = require("@jest/globals");

_getJestObj = () => jest;

return jest;
}

function _hoistedMockFactoryVariable() {
return "/root/project/src/file.js";
}


`;

exports[`babel-plugin-jest-hoist top level mocking: top level mocking 1`] = `

require('x');
Expand Down
30 changes: 30 additions & 0 deletions packages/babel-plugin-jest-hoist/src/__tests__/hoistPlugin.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,43 @@
*
*/

import * as path from 'path';
import pluginTester from 'babel-plugin-tester';
import {format as formatCode} from 'prettier';
import babelPluginJestHoist from '..';

const fakeAbsolutPath = path.resolve(__dirname, '../file.js');

pluginTester({
plugin: babelPluginJestHoist,
pluginName: 'babel-plugin-jest-hoist',
tests: {
'automatic react runtime': {
babelOptions: {
babelrc: false,
configFile: false,
filename: fakeAbsolutPath,
presets: [
[
require.resolve('@babel/preset-react'),
{development: true, runtime: 'automatic'},
],
],
},
code: `
jest.mock('./App', () => () => <div>Hello world</div>);
`,
formatResult(code) {
// replace the filename with something that will be the same across OSes and machine
const codeWithoutSystemPath = code.replace(
new RegExp(fakeAbsolutPath, 'g'),
'/root/project/src/file.js',
);
SimenB marked this conversation as resolved.
Show resolved Hide resolved

return formatCode(codeWithoutSystemPath, {parser: 'babel'});
},
snapshot: true,
},
'top level mocking': {
code: `
require('x');
Expand Down
36 changes: 34 additions & 2 deletions packages/babel-plugin-jest-hoist/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -133,12 +133,38 @@ FUNCTIONS.mock = args => {
}

if (!found) {
SimenB marked this conversation as resolved.
Show resolved Hide resolved
const isAllowedIdentifier =
let isAllowedIdentifier =
(scope.hasGlobal(name) && ALLOWED_IDENTIFIERS.has(name)) ||
/^mock/i.test(name) ||
// Allow istanbul's coverage variable to pass.
/^(?:__)?cov/.test(name);

if (!isAllowedIdentifier) {
const binding = scope.bindings[name];

if (binding?.path.isVariableDeclarator()) {
const initNode = binding.path.node.init;

if (initNode && binding.constant && scope.isPure(initNode, true)) {
const identifier = scope.generateUidIdentifier(
'hoistedMockFactoryVariable',
);

binding.path.parentPath.insertAfter(
createHoistedVariable({
HOISTED_NAME: identifier,
HOISTED_VALUE: binding.path.node.init,
}),
);

// replace reference with a call to the new function
id.replaceWith(callExpression(identifier, []));

isAllowedIdentifier = true;
}
}
}

if (!isAllowedIdentifier) {
throw id.buildCodeFrameError(
'The module factory of `jest.mock()` is not allowed to ' +
Expand Down Expand Up @@ -176,6 +202,12 @@ function GETTER_NAME() {
}
`;

const createHoistedVariable = statement`
function HOISTED_NAME() {
return HOISTED_VALUE;
}
`;

const isJestObject = (expression: NodePath<Expression>): boolean => {
// global
if (
Expand Down Expand Up @@ -273,7 +305,7 @@ export default (): PluginObj<{
visitor: {
ExpressionStatement(exprStmt) {
const jestObjExpr = extractJestObjExprIfHoistable(
exprStmt.get<'expression'>('expression'),
exprStmt.get('expression'),
);
if (jestObjExpr) {
jestObjExpr.replaceWith(
Expand Down
5 changes: 4 additions & 1 deletion yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -1456,7 +1456,7 @@ __metadata:
languageName: node
linkType: hard

"@babel/preset-react@npm:*, @babel/preset-react@npm:^7.0.0, @babel/preset-react@npm:^7.9.4":
"@babel/preset-react@npm:*, @babel/preset-react@npm:^7.0.0, @babel/preset-react@npm:^7.12.1, @babel/preset-react@npm:^7.9.4":
version: 7.12.1
resolution: "@babel/preset-react@npm:7.12.1"
dependencies:
Expand Down Expand Up @@ -4830,13 +4830,16 @@ __metadata:
resolution: "babel-plugin-jest-hoist@workspace:packages/babel-plugin-jest-hoist"
dependencies:
"@babel/core": ^7.11.6
"@babel/preset-react": ^7.12.1
"@babel/template": ^7.3.3
"@babel/types": ^7.3.3
"@types/babel__core": ^7.0.0
"@types/babel__template": ^7.0.2
"@types/babel__traverse": ^7.0.6
"@types/node": "*"
"@types/prettier": ^2.0.0
babel-plugin-tester: ^10.0.0
prettier: ^2.1.1
languageName: unknown
linkType: soft

Expand Down