-
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
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
Cannot dynamic import multiple times a mocked module #7040
Comments
Thanks for the reproduction. It looks like there is some race condition around vitest/packages/vitest/src/runtime/mocker.ts Line 162 in 2ce84d0
vitest/packages/vitest/src/runtime/mocker.ts Line 356 in 2ce84d0
There's a logic to bail out early when cyclic import, but that got kicked in even though this is not a cyclic import. I don't have a fix yet. For now, I prepared a simpler repro for debugging if anyone wants to look into further. https://stackblitz.com/edit/github-r4fmamrp?file=test%2Fautomock.spec.js import { expect, test, vi } from 'vitest';
vi.mock('./factory-target', () => ({ default: 'mocked' }));
test('automock', async () => {
await import('node:path'); // need this to flush `Vitestmocker.resolveMocks`
const all = await Promise.all([
import('./factory-target').then((v) => v.default),
import('./factory-target').then((v) => v.default),
import('./factory-target').then((v) => v.default),
]);
expect(all).toMatchInlineSnapshot(`
[
"mocked",
"original", // <- should be "mocked"
"original", // <
]
`);
}); import { expect, test, vi } from 'vitest';
vi.mock('./automock-target');
test('automock', async () => {
await import('node:path'); // need this to flush `Vitestmocker.resolveMocks`
const all = await Promise.all([
import('./automock-target').then((v) => v.default),
import('./automock-target').then((v) => v.default),
import('./automock-target').then((v) => v.default),
]);
expect(all).toMatchInlineSnapshot(`
[
"original",
undefined, // <- should be "original"
undefined, // <
]
`);
}); |
Thanks a lot for your investigation. I just wanted to share how I found this issue. My test case is far from being the code I had initially 😅 I found this bug with a pretty usual React pattern around lazy loading (written from mobile do sorry for typos): const Authenticated = lazy(() => import('./Authenticated')
function App() {
const isAuthenticated = useIsAuthenticated()
useEffect(() => {
import('./Authenticated') // fire early load while user still logs
})
if (! isAuthenticated) return <Login />
return <Suspense><Authenticated /></Suspense>
} |
Describe the bug
When dynamically importing several times the same mocked module, we may fail to import it on subsequent imports.
Reproduction
The reproduction will be clearer than the description above:
Reproduction at: https://github.com/dubzzz/imported-twice-vitest-bug
System Info
Used Package Manager
npm
Validations
The text was updated successfully, but these errors were encountered: