Skip to content

Commit

Permalink
fix(jasmine-globals): fix transform for existing spyOn (#580)
Browse files Browse the repository at this point in the history
* fix transform for existing `spyOn`

* call `mockRestore` for existing spies
  • Loading branch information
puglyfe authored May 24, 2024
1 parent aa45fa8 commit bb93df3
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 4 deletions.
2 changes: 2 additions & 0 deletions src/transformers/jasmine-globals.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ test('spyOn', () => {
jest.spyOn(stuff).and.resolveTo('lmao');
jest.spyOn(stuff).and.rejectWith('oh no');
const fetchSpy = spyOn(window, 'fetch').and.resolveTo({json: {}});
existingSpy.and.callThrough();
`,
`
jest.spyOn().mockReturnValue();
Expand All @@ -42,6 +43,7 @@ test('spyOn', () => {
jest.spyOn(stuff).mockResolvedValue('lmao');
jest.spyOn(stuff).mockRejectedValue('oh no');
const fetchSpy = jest.spyOn(window, 'fetch').mockResolvedValue({json: {}});
existingSpy.mockRestore();
`
)
})
Expand Down
15 changes: 11 additions & 4 deletions src/transformers/jasmine-globals.ts
Original file line number Diff line number Diff line change
Expand Up @@ -161,10 +161,17 @@ export default function jasmineGlobals(fileInfo, api, options) {
// if it's `*.and.callThrough()` we should remove
// `and.callThrough()` because jest calls through by default
case 'callThrough': {
const { callee } = path.node.callee.object.object
const arg = path.node.callee.object.object.arguments
path.node.callee = callee
path.node.arguments = arg
// if this comes from an `Identifier` (e.g. `existingSpy.and.callThrough()`),
// we assume the intent is to restore an existing spy
// to its original implementation using `*.mockRestore()`
if (path.node.callee.object.object.type === 'Identifier') {
path.node.callee.object = path.node.callee.object.object
path.node.callee.property.name = 'mockRestore'
} else {
// otherwise, we just remove the `.and.callThrough()`
// since this is the default behavior in jest
j(path).replaceWith(path.node.callee.object.object)
}
break
}
// if it's `*.and.callFake()`, replace with jest's
Expand Down

0 comments on commit bb93df3

Please sign in to comment.