Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: should remove mockPath from callstack whether success or failed #3971

Merged
merged 5 commits into from
Aug 21, 2023
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions examples/mocks/src/dynamic-module.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export {}
17 changes: 17 additions & 0 deletions examples/mocks/src/retry-dynamic-import.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
export async function retryDynamicImport() {
let retryTimes = 0
const load = async () => {
try { // eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-expect-error
miserylee marked this conversation as resolved.
Show resolved Hide resolved
return await import('./dynamic-module')
}
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.'))
})
})
12 changes: 7 additions & 5 deletions packages/vitest/src/runtime/mocker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -423,11 +423,13 @@ 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