Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
Prev Previous commit
Next Next commit
Fix jest.mock in jest.mock
  • Loading branch information
nicolo-ribaudo committed Aug 28, 2022
commit b80915c0df0133faaa0a07bbc05c95e38c4c741b
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,56 @@ function _getJestObj() {
}


`;

exports[`babel-plugin-jest-hoist global jest.mock within jest: global jest.mock within jest 1`] = `

jest.mock('some-module', () => {
jest.mock('some-module');
});

↓ ↓ ↓ ↓ ↓ ↓

_getJestObj().mock('some-module', () => {
_getJestObj().mock('some-module');
});

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

_getJestObj = () => jest;

return jest;
}


`;

exports[`babel-plugin-jest-hoist imported jest.mock within jest: imported jest.mock within jest 1`] = `

import {jest} from '@jest/globals';

jest.mock('some-module', () => {
jest.mock('some-module');
});

↓ ↓ ↓ ↓ ↓ ↓

_getJestObj().mock('some-module', () => {
_getJestObj().mock('some-module');
});

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

_getJestObj = () => jest;

return jest;
}

import {jest} from '@jest/globals';


`;

exports[`babel-plugin-jest-hoist required \`jest\` within \`jest\`: required \`jest\` within \`jest\` 1`] = `
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ pluginTester({
formatResult,
snapshot: true,
},
'imported jest within jest': {
'imported jest.mock within jest': {
code: formatResult(`
import {jest} from '@jest/globals';

Expand All @@ -101,6 +101,15 @@ pluginTester({
formatResult,
snapshot: true,
},
'global jest.mock within jest': {
code: formatResult(`
jest.mock('some-module', () => {
jest.mock('some-module');
});
`),
formatResult,
snapshot: true,
},
},
/* eslint-enable */
});
13 changes: 13 additions & 0 deletions packages/babel-plugin-jest-hoist/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -161,6 +161,19 @@ FUNCTIONS.mock = args => {
hoistedVariables.add(node);
isAllowedIdentifier = true;
}
} else if (binding?.path.isImportSpecifier()) {
const importDecl = binding.path
.parentPath as NodePath<ImportDeclaration>;
const imported = binding.path.node.imported;
if (
importDecl.node.source.value === JEST_GLOBALS_MODULE_NAME &&
(isIdentifier(imported) ? imported.name : imported.value) ===
JEST_GLOBALS_MODULE_JEST_EXPORT_NAME
) {
isAllowedIdentifier = true;
// Imports are already hoisted, so we don't need to add it
// to hoistedVariables.
}
}
}

Expand Down