Skip to content

Commit bb93df3

Browse files
authored
fix(jasmine-globals): fix transform for existing spyOn (#580)
* fix transform for existing `spyOn` * call `mockRestore` for existing spies
1 parent aa45fa8 commit bb93df3

File tree

2 files changed

+13
-4
lines changed

2 files changed

+13
-4
lines changed

src/transformers/jasmine-globals.test.ts

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@ test('spyOn', () => {
2828
jest.spyOn(stuff).and.resolveTo('lmao');
2929
jest.spyOn(stuff).and.rejectWith('oh no');
3030
const fetchSpy = spyOn(window, 'fetch').and.resolveTo({json: {}});
31+
existingSpy.and.callThrough();
3132
`,
3233
`
3334
jest.spyOn().mockReturnValue();
@@ -42,6 +43,7 @@ test('spyOn', () => {
4243
jest.spyOn(stuff).mockResolvedValue('lmao');
4344
jest.spyOn(stuff).mockRejectedValue('oh no');
4445
const fetchSpy = jest.spyOn(window, 'fetch').mockResolvedValue({json: {}});
46+
existingSpy.mockRestore();
4547
`
4648
)
4749
})

src/transformers/jasmine-globals.ts

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -161,10 +161,17 @@ export default function jasmineGlobals(fileInfo, api, options) {
161161
// if it's `*.and.callThrough()` we should remove
162162
// `and.callThrough()` because jest calls through by default
163163
case 'callThrough': {
164-
const { callee } = path.node.callee.object.object
165-
const arg = path.node.callee.object.object.arguments
166-
path.node.callee = callee
167-
path.node.arguments = arg
164+
// if this comes from an `Identifier` (e.g. `existingSpy.and.callThrough()`),
165+
// we assume the intent is to restore an existing spy
166+
// to its original implementation using `*.mockRestore()`
167+
if (path.node.callee.object.object.type === 'Identifier') {
168+
path.node.callee.object = path.node.callee.object.object
169+
path.node.callee.property.name = 'mockRestore'
170+
} else {
171+
// otherwise, we just remove the `.and.callThrough()`
172+
// since this is the default behavior in jest
173+
j(path).replaceWith(path.node.callee.object.object)
174+
}
168175
break
169176
}
170177
// if it's `*.and.callFake()`, replace with jest's

0 commit comments

Comments
 (0)