-
-
Notifications
You must be signed in to change notification settings - Fork 9.4k
/
vitest-manager.ts
317 lines (272 loc) · 10.1 KB
/
vitest-manager.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
import { existsSync } from 'node:fs';
import type {
CoverageOptions,
ResolvedCoverageOptions,
TestProject,
TestSpecification,
Vitest,
WorkspaceProject,
} from 'vitest/node';
import { resolvePathInStorybookCache } from 'storybook/internal/common';
import type { TestingModuleRunRequestPayload } from 'storybook/internal/core-events';
import type { DocsIndexEntry, StoryIndex, StoryIndexEntry } from '@storybook/types';
import path, { normalize } from 'pathe';
import slash from 'slash';
import { COVERAGE_DIRECTORY, type Config } from '../constants';
import { log } from '../logger';
import type { StorybookCoverageReporterOptions } from './coverage-reporter';
import { StorybookReporter } from './reporter';
import type { TestManager } from './test-manager';
type TagsFilter = {
include: string[];
exclude: string[];
skip: string[];
};
export class VitestManager {
vitest: Vitest | null = null;
vitestStartupCounter = 0;
storyCountForCurrentRun: number = 0;
constructor(private testManager: TestManager) {}
async startVitest({ watchMode = false, coverage = false } = {}) {
const { createVitest } = await import('vitest/node');
const storybookCoverageReporter: [string, StorybookCoverageReporterOptions] = [
'@storybook/experimental-addon-test/internal/coverage-reporter',
{
testManager: this.testManager,
coverageOptions: this.vitest?.config?.coverage as ResolvedCoverageOptions<'v8'>,
},
];
const coverageOptions = (
coverage
? {
enabled: true,
clean: false,
cleanOnRerun: !watchMode,
reportOnFailure: true,
reporter: [['html', {}], storybookCoverageReporter],
reportsDirectory: resolvePathInStorybookCache(COVERAGE_DIRECTORY),
}
: { enabled: false }
) as CoverageOptions;
this.vitest = await createVitest('test', {
watch: watchMode,
passWithNoTests: false,
changed: watchMode,
// TODO:
// Do we want to enable Vite's default reporter?
// The output in the terminal might be too spamy and it might be better to
// find a way to just show errors and warnings for example
// Otherwise it might be hard for the user to discover Storybook related logs
reporters: ['default', new StorybookReporter(this.testManager)],
coverage: coverageOptions,
});
if (this.vitest) {
this.vitest.onCancel(() => {
// TODO: handle cancellation
});
}
try {
await this.vitest.init();
} catch (e) {
this.testManager.reportFatalError('Failed to init Vitest', e);
}
if (watchMode) {
await this.setupWatchers();
}
}
private updateLastChanged(filepath: string) {
const projects = this.vitest!.getModuleProjects(filepath);
projects.forEach(({ server, browser }) => {
const serverMods = server.moduleGraph.getModulesByFile(filepath);
serverMods?.forEach((mod) => server.moduleGraph.invalidateModule(mod));
if (browser) {
const browserMods = browser.vite.moduleGraph.getModulesByFile(filepath);
browserMods?.forEach((mod) => browser.vite.moduleGraph.invalidateModule(mod));
}
});
}
private async fetchStories(indexUrl: string, requestStoryIds?: string[]) {
try {
const index = (await Promise.race([
fetch(indexUrl).then((res) => res.json()),
new Promise((_, reject) => setTimeout(reject, 3000, new Error('Request took too long'))),
])) as StoryIndex;
const storyIds = requestStoryIds || Object.keys(index.entries);
return storyIds.map((id) => index.entries[id]).filter((story) => story.type === 'story');
} catch (e) {
log('Failed to fetch story index: ' + e.message);
return [];
}
}
private filterStories(
story: StoryIndexEntry | DocsIndexEntry,
moduleId: string,
tagsFilter: TagsFilter
) {
const absoluteImportPath = path.join(process.cwd(), story.importPath);
if (absoluteImportPath !== moduleId) {
return false;
}
if (tagsFilter.include.length && !tagsFilter.include.some((tag) => story.tags?.includes(tag))) {
return false;
}
if (tagsFilter.exclude.some((tag) => story.tags?.includes(tag))) {
return false;
}
// Skipped tests are intentionally included here
return true;
}
async runTests(requestPayload: TestingModuleRunRequestPayload<Config>) {
if (!this.vitest) {
await this.startVitest();
}
this.resetTestNamePattern();
const stories = await this.fetchStories(requestPayload.indexUrl, requestPayload.storyIds);
const vitestTestSpecs = await this.getStorybookTestSpecs();
const isSingleStoryRun = requestPayload.storyIds?.length === 1;
const { filteredTestFiles, totalTestCount } = vitestTestSpecs.reduce(
(acc, spec) => {
/* eslint-disable no-underscore-dangle */
const { env = {} } = spec.project.config;
const include = env.__VITEST_INCLUDE_TAGS__?.split(',').filter(Boolean) ?? ['test'];
const exclude = env.__VITEST_EXCLUDE_TAGS__?.split(',').filter(Boolean) ?? [];
const skip = env.__VITEST_SKIP_TAGS__?.split(',').filter(Boolean) ?? [];
/* eslint-enable no-underscore-dangle */
const matches = stories.filter((story) =>
this.filterStories(story, spec.moduleId, { include, exclude, skip })
);
if (matches.length) {
if (!this.testManager.watchMode) {
// Clear the file cache if watch mode is not enabled
this.updateLastChanged(spec.moduleId);
}
acc.filteredTestFiles.push(spec);
acc.totalTestCount += matches.filter(
// Don't count skipped stories, because StorybookReporter doesn't include them either
(story) => !skip.some((tag) => story.tags?.includes(tag))
).length;
}
return acc;
},
{ filteredTestFiles: [] as TestSpecification[], totalTestCount: 0 }
);
await this.cancelCurrentRun();
this.storyCountForCurrentRun = totalTestCount;
if (isSingleStoryRun) {
const storyName = stories[0].name;
this.vitest!.configOverride.testNamePattern = new RegExp(
`^${storyName.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}$`
);
}
await this.vitest!.runFiles(filteredTestFiles, true);
this.resetTestNamePattern();
}
async cancelCurrentRun() {
await this.vitest?.cancelCurrentRun('keyboard-input');
await this.vitest?.runningPromise;
}
async closeVitest() {
await this.vitest?.close();
}
async getStorybookTestSpecs() {
const globTestSpecs = (await this.vitest?.globTestSpecs()) ?? [];
return (
globTestSpecs.filter((workspaceSpec) => this.isStorybookProject(workspaceSpec.project)) ?? []
);
}
private async getTestDependencies(spec: TestSpecification, deps = new Set<string>()) {
const addImports = async (project: WorkspaceProject, filepath: string) => {
if (deps.has(filepath)) {
return;
}
deps.add(filepath);
const mod = project.server.moduleGraph.getModuleById(filepath);
const transformed =
mod?.ssrTransformResult || (await project.vitenode.transformRequest(filepath));
if (!transformed) {
return;
}
const dependencies = [...(transformed.deps || []), ...(transformed.dynamicDeps || [])];
await Promise.all(
dependencies.map(async (dep) => {
const idPath = await project.server.pluginContainer.resolveId(dep, filepath, {
ssr: true,
});
const fsPath = idPath && !idPath.external && idPath.id.split('?')[0];
if (
fsPath &&
!fsPath.includes('node_modules') &&
!deps.has(fsPath) &&
existsSync(fsPath)
) {
await addImports(project, fsPath);
}
})
);
};
await addImports(spec.project.workspaceProject, spec.moduleId);
deps.delete(spec.moduleId);
return deps;
}
async runAffectedTests(trigger: string) {
if (!this.vitest) {
return;
}
this.resetTestNamePattern();
const globTestFiles = await this.vitest.globTestSpecs();
const testGraphs = await Promise.all(
globTestFiles
.filter((workspace) => this.isStorybookProject(workspace.project))
.map(async (spec) => {
const deps = await this.getTestDependencies(spec);
return [spec, deps] as const;
})
);
const triggerAffectedTests: TestSpecification[] = [];
for (const [workspaceSpec, deps] of testGraphs) {
if (trigger && (trigger === workspaceSpec.moduleId || deps.has(trigger))) {
triggerAffectedTests.push(workspaceSpec);
}
}
if (triggerAffectedTests.length) {
await this.vitest.cancelCurrentRun('keyboard-input');
await this.vitest.runningPromise;
await this.vitest.runFiles(triggerAffectedTests, false);
}
}
async runAffectedTestsAfterChange(file: string) {
const id = slash(file);
this.vitest?.logger.clearHighlightCache(id);
this.updateLastChanged(id);
this.storyCountForCurrentRun = 0;
await this.runAffectedTests(file);
}
async registerVitestConfigListener() {
this.vitest?.server?.watcher.on('change', async (file) => {
file = normalize(file);
const isConfig = file === this.vitest.server.config.configFile;
if (isConfig) {
log('Restarting Vitest due to config change');
await this.closeVitest();
await this.startVitest();
}
});
}
async setupWatchers() {
this.resetTestNamePattern();
this.vitest?.server?.watcher.removeAllListeners('change');
this.vitest?.server?.watcher.removeAllListeners('add');
this.vitest?.server?.watcher.on('change', this.runAffectedTestsAfterChange.bind(this));
this.vitest?.server?.watcher.on('add', this.runAffectedTestsAfterChange.bind(this));
this.registerVitestConfigListener();
}
resetTestNamePattern() {
if (this.vitest) {
this.vitest.configOverride.testNamePattern = undefined;
}
}
isStorybookProject(project: TestProject | WorkspaceProject) {
// eslint-disable-next-line no-underscore-dangle
return !!project.config.env?.__STORYBOOK_URL__;
}
}