Skip to content

Commit

Permalink
Hoist also jest.* calls that are not expression statements
Browse files Browse the repository at this point in the history
  • Loading branch information
jsnajdr committed Feb 28, 2023
1 parent ddac69b commit 6b9af46
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 8 deletions.
Expand Up @@ -220,8 +220,8 @@ jest.mock('some-module', () => {
↓ ↓ ↓ ↓ ↓ ↓
_getJestObj().mock('some-module', () => {
const actual = jest.requireActual('some-module');
return jest.fn();
const actual = _getJestObj().requireActual('some-module');
return _getJestObj().fn();
});
function _getJestObj() {
const {jest} = require('@jest/globals');
Expand All @@ -243,7 +243,7 @@ jest.mock('some-module', () => {
↓ ↓ ↓ ↓ ↓ ↓
_getJestObj().mock('some-module', () => {
const module = jest.requireActual('some-module');
const module = _getJestObj().requireActual('some-module');
_getJestObj().spyOn(module, 'add');
return module;
});
Expand Down Expand Up @@ -271,7 +271,7 @@ jest.mock('some-module', () => {
↓ ↓ ↓ ↓ ↓ ↓
_getJestObj().mock('some-module', () => {
const Actual = jest.requireActual('some-module');
const Actual = _getJestObj().requireActual('some-module');
return class Mocked extends Actual {
constructor() {
super();
Expand All @@ -286,3 +286,25 @@ function _getJestObj() {
}
`;

exports[`babel-plugin-jest-hoist 13. jest.mock call nested inside a statement: 13. jest.mock call nested inside a statement 1`] = `
jest.mock('someModule', () => {
require('x');
expect(jest.mock('someNode')).toBe(1);
});
↓ ↓ ↓ ↓ ↓ ↓
_getJestObj().mock('someModule', () => {
expect(_getJestObj().mock('someNode')).toBe(1);
require('x');
});
function _getJestObj() {
const {jest} = require('@jest/globals');
_getJestObj = () => jest;
return jest;
}
`;
10 changes: 10 additions & 0 deletions packages/babel-plugin-jest-hoist/src/__tests__/hoistPlugin.test.ts
Expand Up @@ -177,6 +177,16 @@ pluginTester({
formatResult,
snapshot: true,
},
'jest.mock call nested inside a statement': {
code: formatResult(`
jest.mock('someModule', () => {
require('x');
expect(jest.mock('someNode')).toBe(1);
});
`),
formatResult,
snapshot: true,
},
},
/* eslint-enable */
});
6 changes: 2 additions & 4 deletions packages/babel-plugin-jest-hoist/src/index.ts
Expand Up @@ -340,10 +340,8 @@ export default function jestHoist(): PluginObj<{
};
},
visitor: {
ExpressionStatement(exprStmt) {
const jestObjInfo = extractJestObjExprIfHoistable(
exprStmt.get('expression'),
);
CallExpression(callExpr) {
const jestObjInfo = extractJestObjExprIfHoistable(callExpr);
if (jestObjInfo) {
const jestCallExpr = callExpression(
this.declareJestObjGetterIdentifier(),
Expand Down

0 comments on commit 6b9af46

Please sign in to comment.