Skip to content

Commit

Permalink
feat: update jest.mock imports with migrate js-to-jsx script (#905)
Browse files Browse the repository at this point in the history
Handles `jest.mock('../path/to/file.js', () => {})` imports
  • Loading branch information
KaiVandivier authored Jan 28, 2025
1 parent bbe3d21 commit 1d67a77
Showing 1 changed file with 44 additions and 0 deletions.
44 changes: 44 additions & 0 deletions cli/src/commands/migrate/js-to-jsx.js
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,11 @@ const resolveImportSource = ({
return isRenamed ? importSourceWithExtension + 'x' : importSource
}

const isJestMock = (callee) =>
callee.type === 'MemberExpression' &&
callee.object?.name === 'jest' &&
callee.property?.name === 'mock'

const updateImports = async ({
filepath,
renamedFiles,
Expand Down Expand Up @@ -132,6 +137,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) {
Expand Down

0 comments on commit 1d67a77

Please sign in to comment.