From 8666a28278c92d304723926fe000231efb7e0d34 Mon Sep 17 00:00:00 2001 From: Kai Vandivier Date: Fri, 24 Jan 2025 18:36:34 +0100 Subject: [PATCH] feat: update jest.mock imports with migrate js-to-jsx script --- cli/src/commands/migrate/js-to-jsx.js | 39 +++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) diff --git a/cli/src/commands/migrate/js-to-jsx.js b/cli/src/commands/migrate/js-to-jsx.js index d2924a08..482d23ae 100644 --- a/cli/src/commands/migrate/js-to-jsx.js +++ b/cli/src/commands/migrate/js-to-jsx.js @@ -132,6 +132,45 @@ const updateImports = async ({ contentUpdated = true } }, + // Triggers on function calls -- we're looking for `jest.mock()` + CallExpression: (astPath) => { + const { callee } = astPath.node + if (!isJestMock(callee)) { + return + } + + const mockFileSource = astPath.node.arguments[0].value + if (!mockFileSource.startsWith('.')) { + return // It's not a relative import; skip this one + } + + const newMockFileSource = resolveImportSource({ + filepath, + importSource: mockFileSource, + renamedFiles, + skipUpdatingImportsWithoutExtension, + }) + + // Since generating code from babel doesn't respect formatting, + // update imports with just string replacement + if (newMockFileSource !== mockFileSource) { + // updating & replacing the raw value, which includes quotes, + // ends up being more precise and avoids side effects + const rawImportSource = astPath.node.arguments[0].extra.raw + const newRawImportSource = rawImportSource.replace( + mockFileSource, + newMockFileSource + ) + reporter.debug( + ` Replacing ${mockFileSource} => ${newMockFileSource}` + ) + newCode = newCode.replace( + rawImportSource, + newRawImportSource + ) + contentUpdated = true + } + }, }) if (contentUpdated) {