Skip to content

Commit

Permalink
fix: should remove mockPath from callstack whether success or failed (#…
Browse files Browse the repository at this point in the history
…3971)

Co-authored-by: lijifei <lijifei@bytedance.com>
  • Loading branch information
miserylee and lijifei authored Aug 21, 2023
1 parent 74dc596 commit 5eb8561
Show file tree
Hide file tree
Showing 4 changed files with 42 additions and 5 deletions.
1 change: 1 addition & 0 deletions examples/mocks/src/dynamic-module.js
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export {}
16 changes: 16 additions & 0 deletions examples/mocks/src/retry-dynamic-import.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
export async function retryDynamicImport() {
let retryTimes = 0
const load = async () => {
try {
return await import('./dynamic-module.js')
}
catch (e) {
if (retryTimes === 3)
throw new Error('import dynamic module failed.')
retryTimes += 1
return await load()
}
}

return await load()
}
17 changes: 17 additions & 0 deletions examples/mocks/test/retry-dynamic-import.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import { retryDynamicImport } from '../src/retry-dynamic-import'

vi.mock('../src/dynamic-module', () => {
return { foo: 'bar' }
})

describe('retry-dynamic-import', () => {
it('should dynamic import module success', async () => {
expect(await retryDynamicImport()).toEqual({ foo: 'bar' })
})
it('should throw when retry over 3 times', async () => {
vi.doMock('../src/dynamic-module', () => {
throw new Error('foobar')
})
await expect(retryDynamicImport()).rejects.toThrowError(new Error('import dynamic module failed.'))
})
})
13 changes: 8 additions & 5 deletions packages/vitest/src/runtime/mocker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -423,11 +423,14 @@ export class VitestMocker {
return exports
}
if (typeof mock === 'function' && !callstack.includes(mockPath) && !callstack.includes(url)) {
callstack.push(mockPath)
const result = await this.callFunctionMock(mockPath, mock)
const indexMock = callstack.indexOf(mockPath)
callstack.splice(indexMock, 1)
return result
try {
callstack.push(mockPath)
return await this.callFunctionMock(mockPath, mock)
}
finally {
const indexMock = callstack.indexOf(mockPath)
callstack.splice(indexMock, 1)
}
}
if (typeof mock === 'string' && !callstack.includes(mock))
return mock
Expand Down

0 comments on commit 5eb8561

Please sign in to comment.