From 952c31dfc4706f3f4fd2cb84a253ce8ea2b11e9c Mon Sep 17 00:00:00 2001 From: Vladimir Date: Tue, 16 Jan 2024 13:49:07 +0100 Subject: [PATCH] fix(vitest): correctly find module if it has a version query (#4976) --- packages/vite-node/src/server.ts | 26 +++++++++++++++++++++++++- packages/vitest/src/node/core.ts | 6 ++++++ 2 files changed, 31 insertions(+), 1 deletion(-) diff --git a/packages/vite-node/src/server.ts b/packages/vite-node/src/server.ts index de68171d5539..0a137b25f383 100644 --- a/packages/vite-node/src/server.ts +++ b/packages/vite-node/src/server.ts @@ -195,6 +195,30 @@ export class ViteNodeServer { return 'web' } + private getChangedModule( + id: string, + file: string, + ) { + const module = this.server.moduleGraph.getModuleById(id) || this.server.moduleGraph.getModuleById(file) + if (module) + return module + const _modules = this.server.moduleGraph.getModulesByFile(file) + if (!_modules || !_modules.size) + return null + // find the latest changed module + const modules = [..._modules] + let mod = modules[0] + let latestMax = -1 + for (const m of _modules) { + const timestamp = Math.max(m.lastHMRTimestamp, m.lastInvalidationTimestamp) + if (timestamp > latestMax) { + latestMax = timestamp + mod = m + } + } + return mod + } + private async _fetchModule(id: string, transformMode: 'web' | 'ssr'): Promise { let result: FetchResult @@ -212,7 +236,7 @@ export class ViteNodeServer { const { path: filePath } = toFilePath(id, this.server.config.root) - const moduleNode = this.server.moduleGraph.getModuleById(id) || this.server.moduleGraph.getModuleById(filePath) + const moduleNode = this.getChangedModule(id, filePath) const cache = this.fetchCaches[transformMode].get(filePath) // lastUpdateTimestamp is the timestamp that marks the last time the module was changed diff --git a/packages/vitest/src/node/core.ts b/packages/vitest/src/node/core.ts index 2a5d94693fc1..c9d531b16c95 100644 --- a/packages/vitest/src/node/core.ts +++ b/packages/vitest/src/node/core.ts @@ -705,6 +705,12 @@ export class Vitest { this.changedTests.add(id) this.scheduleRerun([id]) } + else { + // it's possible that file was already there but watcher triggered "add" event instead + const needsRerun = this.handleFileChanged(id) + if (needsRerun.length) + this.scheduleRerun(needsRerun) + } } const watcher = this.server.watcher