Skip to content

Commit

Permalink
feat: can identify fetch mock in esm
Browse files Browse the repository at this point in the history
  • Loading branch information
wheresrhys committed Aug 31, 2024
1 parent 23201b0 commit e523711
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 28 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -46,11 +46,11 @@ describe('identifying fetch-mock instances', () => {
it('esm import named something else', () => {
expectCodemodResult(
`
import fetchMock as fetchNot from 'fetch-mock';
import fetchNot from 'fetch-mock';
fetchNot.mock("blah", 200)
`,
`
import fetchMock as fetchNot from 'fetch-mock';
import fetchNot from 'fetch-mock';
fetchNot.route("blah", 200)
`,
);
Expand Down
68 changes: 42 additions & 26 deletions packages/codemods/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,15 +7,30 @@ import type {
} from 'jscodeshift';
export function codemod(source: string, j: JSCodeshift) {
const root = j(source);
const fetchMockVariableName = root
.find(j.CallExpression, {
callee: {
name: 'require',
},
arguments: [{ value: 'fetch-mock' }],
})
.closest(j.VariableDeclarator)
.get().value.id.name;
let fetchMockVariableName;
try {
fetchMockVariableName = root
.find(j.CallExpression, {
callee: {
name: 'require',
},
arguments: [{ value: 'fetch-mock' }],
})
.closest(j.VariableDeclarator)
.get().value.id.name;
} catch {
try {
fetchMockVariableName = root
.find(j.ImportDeclaration, {
source: { value: 'fetch-mock' },
})
.find(j.ImportDefaultSpecifier)
.get().value.local.name;
console.log(fetchMockVariableName);
} catch (err) {
console.log(err);
}
}

const configSets = root
.find(j.CallExpression, {
Expand Down Expand Up @@ -65,14 +80,16 @@ export function codemod(source: string, j: JSCodeshift) {
})
.remove();

const fetchMockMethodCalls = root.find(j.CallExpression, {
callee: {
object: {
type: 'Identifier',
name: fetchMockVariableName,
const fetchMockMethodCalls = root
.find(j.CallExpression, {
callee: {
object: {
type: 'Identifier',
name: fetchMockVariableName,
},
},
},
}).map((path) => {
})
.map((path) => {
const paths = [path];
while (path.parentPath.value.type !== 'ExpressionStatement') {
path = path.parentPath;
Expand All @@ -82,16 +99,15 @@ export function codemod(source: string, j: JSCodeshift) {
}
return paths;
});

fetchMockMethodCalls
.forEach((path) => {
const callee = path.value.callee as MemberExpression;
const property = callee.property as Identifier;
const method = property.name;
if (method === 'mock') {
property.name = 'route';
}
});

fetchMockMethodCalls.forEach((path) => {
const callee = path.value.callee as MemberExpression;
const property = callee.property as Identifier;
const method = property.name;
if (method === 'mock') {
property.name = 'route';
}
});

return root.toSource();
}
Expand Down

0 comments on commit e523711

Please sign in to comment.