Skip to content

Commit 5eb8561

Browse files
miseryleelijifei
and
lijifei
authored
fix: should remove mockPath from callstack whether success or failed (#3971)
Co-authored-by: lijifei <lijifei@bytedance.com>
1 parent 74dc596 commit 5eb8561

File tree

4 files changed

+42
-5
lines changed

4 files changed

+42
-5
lines changed

examples/mocks/src/dynamic-module.js

+1
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
export {}
+16
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
export async function retryDynamicImport() {
2+
let retryTimes = 0
3+
const load = async () => {
4+
try {
5+
return await import('./dynamic-module.js')
6+
}
7+
catch (e) {
8+
if (retryTimes === 3)
9+
throw new Error('import dynamic module failed.')
10+
retryTimes += 1
11+
return await load()
12+
}
13+
}
14+
15+
return await load()
16+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
import { retryDynamicImport } from '../src/retry-dynamic-import'
2+
3+
vi.mock('../src/dynamic-module', () => {
4+
return { foo: 'bar' }
5+
})
6+
7+
describe('retry-dynamic-import', () => {
8+
it('should dynamic import module success', async () => {
9+
expect(await retryDynamicImport()).toEqual({ foo: 'bar' })
10+
})
11+
it('should throw when retry over 3 times', async () => {
12+
vi.doMock('../src/dynamic-module', () => {
13+
throw new Error('foobar')
14+
})
15+
await expect(retryDynamicImport()).rejects.toThrowError(new Error('import dynamic module failed.'))
16+
})
17+
})

packages/vitest/src/runtime/mocker.ts

+8-5
Original file line numberDiff line numberDiff line change
@@ -423,11 +423,14 @@ export class VitestMocker {
423423
return exports
424424
}
425425
if (typeof mock === 'function' && !callstack.includes(mockPath) && !callstack.includes(url)) {
426-
callstack.push(mockPath)
427-
const result = await this.callFunctionMock(mockPath, mock)
428-
const indexMock = callstack.indexOf(mockPath)
429-
callstack.splice(indexMock, 1)
430-
return result
426+
try {
427+
callstack.push(mockPath)
428+
return await this.callFunctionMock(mockPath, mock)
429+
}
430+
finally {
431+
const indexMock = callstack.indexOf(mockPath)
432+
callstack.splice(indexMock, 1)
433+
}
431434
}
432435
if (typeof mock === 'string' && !callstack.includes(mock))
433436
return mock

0 commit comments

Comments
 (0)