vitest 0.0.33 → 0.0.37

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (62) hide show
  1. package/README.gh.md +67 -11
  2. package/dist/chunk-4OVO6RD6.js +1 -0
  3. package/dist/chunk-CUG6SVUZ.js +1 -0
  4. package/dist/chunk-F27UALKJ.js +1 -0
  5. package/dist/chunk-XPSQDVUG.js +1 -0
  6. package/dist/global-CKRMAXWF.js +1 -0
  7. package/dist/happy-dom-RNJZR3YC.js +1 -0
  8. package/dist/index.d.ts +73 -6
  9. package/dist/index.js +1 -4
  10. package/dist/jsdom-6QAZGE6T.js +1 -0
  11. package/dist/node/cli.d.ts +5 -1
  12. package/dist/node/cli.js +7 -86
  13. package/dist/node/entry.d.ts +1 -1
  14. package/dist/node/entry.js +19 -12
  15. package/dist/types-d3253f2d.d.ts +213 -0
  16. package/package.json +9 -4
  17. package/dist/constants.d.ts +0 -3
  18. package/dist/constants.js +0 -23
  19. package/dist/context.d.ts +0 -2
  20. package/dist/context.js +0 -4
  21. package/dist/integrations/chai/index.d.ts +0 -3
  22. package/dist/integrations/chai/index.js +0 -3
  23. package/dist/integrations/chai/jest-expect.d.ts +0 -2
  24. package/dist/integrations/chai/jest-expect.js +0 -67
  25. package/dist/integrations/chai/setup.d.ts +0 -2
  26. package/dist/integrations/chai/setup.js +0 -11
  27. package/dist/integrations/chai/snapshot/index.d.ts +0 -8
  28. package/dist/integrations/chai/snapshot/index.js +0 -27
  29. package/dist/integrations/chai/snapshot/manager.d.ts +0 -30
  30. package/dist/integrations/chai/snapshot/manager.js +0 -77
  31. package/dist/integrations/chai/snapshot/utils/jest-config-helper.d.ts +0 -3
  32. package/dist/integrations/chai/snapshot/utils/jest-config-helper.js +0 -39
  33. package/dist/integrations/chai/snapshot/utils/jest-reporters-lite.d.ts +0 -2
  34. package/dist/integrations/chai/snapshot/utils/jest-reporters-lite.js +0 -71
  35. package/dist/integrations/chai/snapshot/utils/jest-test-result-helper.d.ts +0 -6
  36. package/dist/integrations/chai/snapshot/utils/jest-test-result-helper.js +0 -66
  37. package/dist/integrations/chai/snapshot/utils/types.d.ts +0 -29
  38. package/dist/integrations/chai/snapshot/utils/types.js +0 -1
  39. package/dist/integrations/chai/types.d.ts +0 -3
  40. package/dist/integrations/chai/types.js +0 -1
  41. package/dist/integrations/global.d.ts +0 -1
  42. package/dist/integrations/global.js +0 -8
  43. package/dist/integrations/jsdom/index.d.ts +0 -5
  44. package/dist/integrations/jsdom/index.js +0 -21
  45. package/dist/integrations/jsdom/keys.d.ts +0 -1
  46. package/dist/integrations/jsdom/keys.js +0 -220
  47. package/dist/integrations/sinon.d.ts +0 -3
  48. package/dist/integrations/sinon.js +0 -5
  49. package/dist/node/node.d.ts +0 -23
  50. package/dist/node/node.js +0 -159
  51. package/dist/reporters/default.d.ts +0 -24
  52. package/dist/reporters/default.js +0 -149
  53. package/dist/reporters/error.d.ts +0 -9
  54. package/dist/reporters/error.js +0 -182
  55. package/dist/run/index.d.ts +0 -8
  56. package/dist/run/index.js +0 -248
  57. package/dist/suite.d.ts +0 -26
  58. package/dist/suite.js +0 -91
  59. package/dist/types.d.ts +0 -138
  60. package/dist/types.js +0 -1
  61. package/dist/utils/hook.d.ts +0 -5
  62. package/dist/utils/hook.js +0 -14
@@ -1,149 +0,0 @@
1
- /* eslint-disable no-console */
2
- import { performance } from 'perf_hooks';
3
- import { relative } from 'path';
4
- import c from 'picocolors';
5
- import Listr from 'listr';
6
- import { printError } from './error';
7
- const CROSS = '✖ ';
8
- export class DefaultReporter {
9
- constructor() {
10
- this.start = 0;
11
- this.end = 0;
12
- this.listr = null;
13
- this.listrPromise = null;
14
- this.taskMap = new Map();
15
- this.cwd = process.cwd();
16
- }
17
- relative(path) {
18
- return relative(this.cwd, path);
19
- }
20
- onStart(config) {
21
- this.cwd = config.root;
22
- console.log(c.green(`Running tests under ${c.gray(this.cwd)}\n`));
23
- }
24
- onCollected(files) {
25
- this.start = performance.now();
26
- this.taskMap = new Map();
27
- const tasks = files.reduce((acc, file) => acc.concat(file.suites.flatMap(i => i.tasks)), []);
28
- tasks.forEach((t) => {
29
- const obj = {};
30
- obj.promise = new Promise((resolve, reject) => {
31
- obj.resolve = resolve;
32
- obj.reject = reject;
33
- });
34
- this.taskMap.set(t, obj);
35
- });
36
- const createTasksListr = (tasks) => {
37
- return tasks.map((task) => {
38
- return {
39
- title: task.name,
40
- skip: () => task.mode === 'skip',
41
- task: async () => {
42
- var _a;
43
- return await ((_a = this.taskMap.get(task)) === null || _a === void 0 ? void 0 : _a.promise);
44
- },
45
- };
46
- });
47
- };
48
- const listrOptions = {
49
- exitOnError: false,
50
- };
51
- this.listr = new Listr(files.map((file) => {
52
- return {
53
- title: this.relative(file.filepath),
54
- task: () => {
55
- if (file.error)
56
- throw file.error;
57
- const suites = file.suites.filter(i => i.tasks.length);
58
- if (!suites.length)
59
- throw new Error('No tasks found');
60
- return new Listr(suites.flatMap((suite) => {
61
- if (!suite.name)
62
- return createTasksListr(suite.tasks);
63
- return [{
64
- title: suite.name,
65
- skip: () => suite.mode !== 'run',
66
- task: () => new Listr(createTasksListr(suite.tasks), listrOptions),
67
- }];
68
- }), listrOptions);
69
- },
70
- };
71
- }), listrOptions);
72
- this.listrPromise = this.listr.run().catch(() => { });
73
- }
74
- onTaskEnd(task) {
75
- var _a, _b;
76
- if (task.state === 'fail')
77
- (_a = this.taskMap.get(task)) === null || _a === void 0 ? void 0 : _a.reject(task.error);
78
- else
79
- (_b = this.taskMap.get(task)) === null || _b === void 0 ? void 0 : _b.resolve();
80
- }
81
- async onFinished(ctx, files = ctx.files) {
82
- var _a;
83
- await this.listrPromise;
84
- this.end = performance.now();
85
- console.log();
86
- const snapshot = ctx.snapshotManager.report();
87
- if (snapshot)
88
- console.log(snapshot.join('\n'));
89
- const suites = files.flatMap(i => i.suites);
90
- const tasks = suites.flatMap(i => i.tasks);
91
- const failedFiles = files.filter(i => i.error);
92
- const failedSuites = suites.filter(i => i.error);
93
- const runnable = tasks.filter(i => i.state === 'pass' || i.state === 'fail');
94
- const passed = tasks.filter(i => i.state === 'pass');
95
- const failed = tasks.filter(i => i.state === 'fail');
96
- const skipped = tasks.filter(i => i.state === 'skip');
97
- const todo = tasks.filter(i => i.state === 'todo');
98
- if (failedFiles.length) {
99
- console.error(c.red(c.bold(`\nFailed to parse ${failedFiles.length} files:`)));
100
- for (const file of failedFiles)
101
- console.error(c.red(`- ${file.filepath}`));
102
- console.log();
103
- for (const file of failedFiles) {
104
- await printError(file.error);
105
- console.log();
106
- }
107
- }
108
- if (failedSuites.length) {
109
- console.error(c.bold(c.red(`\nFailed to run ${failedSuites.length} suites:`)));
110
- for (const suite of failedSuites) {
111
- console.error(c.red(`\n- ${(_a = suite.file) === null || _a === void 0 ? void 0 : _a.filepath} > ${suite.name}`));
112
- await printError(suite.error);
113
- console.log();
114
- }
115
- }
116
- if (failed.length) {
117
- console.error(c.bold(c.red(`\nFailed Tests (${failed.length})`)));
118
- for (const task of failed) {
119
- console.error(`${c.red(`\n${CROSS + c.inverse(' FAIL ')}`)} ${[task.suite.name, task.name].filter(Boolean).join(' > ')}`);
120
- await printError(task.error);
121
- console.log();
122
- }
123
- }
124
- console.log(c.bold(c.green(`Passed ${passed.length} / ${runnable.length}`)));
125
- if (failed.length)
126
- console.log(c.bold(c.red(`Failed ${failed.length} / ${runnable.length}`)));
127
- if (skipped.length)
128
- console.log(c.yellow(`Skipped ${skipped.length}`));
129
- if (todo.length)
130
- console.log(c.dim(`Todo ${todo.length}`));
131
- console.log(`Time ${(this.end - this.start).toFixed(2)}ms`);
132
- }
133
- async onWatcherStart(ctx) {
134
- await this.listrPromise;
135
- const failed = ctx.tasks.filter(i => i.state === 'fail');
136
- if (failed.length)
137
- console.log(`\n${c.bold(c.inverse(c.red(' FAIL ')))}${c.red(` ${failed.length} tests failed. Watching for file changes...`)}`);
138
- else
139
- console.log(`\n${c.bold(c.inverse(c.green(' PASS ')))}${c.green(' Watching for file changes...')}`);
140
- }
141
- async onWatcherRerun(files, trigger) {
142
- await this.listrPromise;
143
- console.clear();
144
- console.log(c.blue('Re-running tests...') + c.dim(` [ ${this.relative(trigger)} ]\n`));
145
- }
146
- // TODO:
147
- onSnapshotUpdate() {
148
- }
149
- }
@@ -1,9 +0,0 @@
1
- export declare function printError(error: unknown): Promise<void>;
2
- interface Poisition {
3
- line: number;
4
- column: number;
5
- }
6
- export declare function posToNumber(source: string, pos: number | Poisition): number;
7
- export declare function numberToPos(source: string, offset: number | Poisition): Poisition;
8
- export declare function generateCodeFrame(source: string, start?: number | Poisition, end?: number, range?: number): string;
9
- export {};
@@ -1,182 +0,0 @@
1
- /* eslint-disable no-console */
2
- import { promises as fs, existsSync } from 'fs';
3
- import c from 'picocolors';
4
- import * as diff from 'diff';
5
- import { notNullish } from '@antfu/utils';
6
- import { SourceMapConsumer } from 'source-map';
7
- export async function printError(error) {
8
- if (!(error instanceof Error)) {
9
- console.error(error);
10
- return;
11
- }
12
- const { modulesTransformResult } = process.__vite_node__;
13
- const e = error;
14
- let codeFramePrinted = false;
15
- const stacks = parseStack(e.stack || '');
16
- const nearest = stacks.find(stack => modulesTransformResult.has(stack.file));
17
- if (nearest) {
18
- const transformResult = modulesTransformResult.get(nearest.file);
19
- const pos = await getOriginalPos(transformResult === null || transformResult === void 0 ? void 0 : transformResult.map, nearest);
20
- if (pos && existsSync(nearest.file)) {
21
- const sourceCode = await fs.readFile(nearest.file, 'utf-8');
22
- console.error(`${c.red(`${c.bold(e.name)}: ${e.message}`)}`);
23
- console.log(c.gray(`${nearest.file}:${pos.line}:${pos.column}`));
24
- console.log(c.yellow(generateCodeFrame(sourceCode, pos)));
25
- codeFramePrinted = true;
26
- }
27
- }
28
- if (!codeFramePrinted)
29
- console.error(e);
30
- if (e.showDiff)
31
- console.error(c.gray(generateDiff(stringify(e.actual), stringify(e.expected))));
32
- }
33
- function getOriginalPos(map, { line, column }) {
34
- return new Promise((resolve) => {
35
- if (!map)
36
- return resolve(null);
37
- SourceMapConsumer.with(map, null, (consumer) => {
38
- const pos = consumer.originalPositionFor({ line, column });
39
- if (pos.line != null && pos.column != null)
40
- resolve(pos);
41
- else
42
- resolve(null);
43
- });
44
- });
45
- }
46
- const splitRE = /\r?\n/;
47
- export function posToNumber(source, pos) {
48
- if (typeof pos === 'number')
49
- return pos;
50
- const lines = source.split(splitRE);
51
- const { line, column } = pos;
52
- let start = 0;
53
- for (let i = 0; i < line - 1; i++)
54
- start += lines[i].length + 1;
55
- return start + column;
56
- }
57
- export function numberToPos(source, offset) {
58
- if (typeof offset !== 'number')
59
- return offset;
60
- if (offset > source.length) {
61
- throw new Error(`offset is longer than source length! offset ${offset} > length ${source.length}`);
62
- }
63
- const lines = source.split(splitRE);
64
- let counted = 0;
65
- let line = 0;
66
- let column = 0;
67
- for (; line < lines.length; line++) {
68
- const lineLength = lines[line].length + 1;
69
- if (counted + lineLength >= offset) {
70
- column = offset - counted + 1;
71
- break;
72
- }
73
- counted += lineLength;
74
- }
75
- return { line: line + 1, column };
76
- }
77
- export function generateCodeFrame(source, start = 0, end, range = 2) {
78
- start = posToNumber(source, start);
79
- end = end || start;
80
- const lines = source.split(splitRE);
81
- let count = 0;
82
- const res = [];
83
- for (let i = 0; i < lines.length; i++) {
84
- count += lines[i].length + 1;
85
- if (count >= start) {
86
- for (let j = i - range; j <= i + range || end > count; j++) {
87
- if (j < 0 || j >= lines.length)
88
- continue;
89
- const line = j + 1;
90
- res.push(`${c.gray(`${line}${' '.repeat(Math.max(3 - String(line).length, 0))}|`)} ${lines[j]}`);
91
- const lineLength = lines[j].length;
92
- if (j === i) {
93
- // push underline
94
- const pad = start - (count - lineLength) + 1;
95
- const length = Math.max(1, end > count ? lineLength - pad : end - start);
96
- res.push(`${c.gray(' |')} ${' '.repeat(pad)}${'^'.repeat(length)}`);
97
- }
98
- else if (j > i) {
99
- if (end > count) {
100
- const length = Math.max(Math.min(end - count, lineLength), 1);
101
- res.push(`${c.gray(' |')} ${'^'.repeat(length)}`);
102
- }
103
- count += lineLength + 1;
104
- }
105
- }
106
- break;
107
- }
108
- }
109
- return res.join('\n');
110
- }
111
- function stringify(obj) {
112
- // TODO: handle more types
113
- return String(obj);
114
- }
115
- const stackFnCallRE = /at (.*) \((.+):(\d+):(\d+)\)$/;
116
- const stackBarePathRE = /at ()(.+):(\d+):(\d+)$/;
117
- function parseStack(stack) {
118
- const lines = stack.split('\n');
119
- const stackFrames = lines.map((raw) => {
120
- const line = raw.trim();
121
- const match = line.match(stackFnCallRE) || line.match(stackBarePathRE);
122
- if (!match)
123
- return null;
124
- let file = match[2];
125
- if (file.startsWith('file://'))
126
- file = file.slice(7);
127
- return {
128
- method: match[1],
129
- file: match[2],
130
- line: parseInt(match[3]),
131
- column: parseInt(match[4]),
132
- };
133
- });
134
- return stackFrames.filter(notNullish);
135
- }
136
- /**
137
- * Returns a diff between 2 strings with coloured ANSI output.
138
- *
139
- * @description
140
- * The diff will be either inline or unified dependent on the value
141
- * of `Base.inlineDiff`.
142
- *
143
- * @param {string} actual
144
- * @param {string} expected
145
- * @return {string} Diff
146
- */
147
- function generateDiff(actual, expected) {
148
- const diffSize = 2048;
149
- if (actual.length > diffSize)
150
- actual = `${actual.substring(0, diffSize)} ... Lines skipped`;
151
- if (expected.length > diffSize)
152
- expected = `${expected.substring(0, diffSize)} ... Lines skipped`;
153
- return unifiedDiff(actual, expected);
154
- }
155
- /**
156
- * Returns unified diff between two strings with coloured ANSI output.
157
- *
158
- * @private
159
- * @param {String} actual
160
- * @param {String} expected
161
- * @return {string} The diff.
162
- */
163
- function unifiedDiff(actual, expected) {
164
- const indent = ' ';
165
- function cleanUp(line) {
166
- if (line[0] === '+')
167
- return indent + c.green(`${line[0]} ${line.slice(1)}`);
168
- if (line[0] === '-')
169
- return indent + c.red(`${line[0]} ${line.slice(1)}`);
170
- if (line.match(/@@/))
171
- return '--';
172
- if (line.match(/\\ No newline/))
173
- return null;
174
- return indent + line;
175
- }
176
- const msg = diff.createPatch('string', actual, expected);
177
- const lines = msg.split('\n').splice(5);
178
- return (`\n${indent}${c.red('- actual')}\n${indent}${c.green('+ expected')}\n\n${lines.map(cleanUp).filter(notBlank).join('\n')}`);
179
- }
180
- function notBlank(line) {
181
- return typeof line !== 'undefined' && line !== null;
182
- }
@@ -1,8 +0,0 @@
1
- import { File, ResolvedConfig, Task, RunnerContext, Suite } from '../types';
2
- export declare function runTask(task: Task, ctx: RunnerContext): Promise<void>;
3
- export declare function collectFiles(paths: string[]): Promise<Record<string, File>>;
4
- export declare function runSuite(suite: Suite, ctx: RunnerContext): Promise<void>;
5
- export declare function runFile(file: File, ctx: RunnerContext): Promise<void>;
6
- export declare function runFiles(filesMap: Record<string, File>, ctx: RunnerContext): Promise<void>;
7
- export declare function run(config: ResolvedConfig): Promise<void>;
8
- export declare function startWatcher(ctx: RunnerContext): Promise<void>;
package/dist/run/index.js DELETED
@@ -1,248 +0,0 @@
1
- import fg from 'fast-glob';
2
- import { setupChai } from '../integrations/chai/setup';
3
- import { clearContext, defaultSuite } from '../suite';
4
- import { context } from '../context';
5
- import { DefaultReporter } from '../reporters/default';
6
- import { defaultIncludes, defaultExcludes } from '../constants';
7
- import { getSnapshotManager } from '../integrations/chai/snapshot';
8
- async function callHook(suite, name, args) {
9
- await Promise.all(suite.hooks[name].map(fn => fn(...args)));
10
- }
11
- export async function runTask(task, ctx) {
12
- var _a, _b, _c;
13
- const { reporter } = ctx;
14
- (_a = getSnapshotManager()) === null || _a === void 0 ? void 0 : _a.setTask(task);
15
- await ((_b = reporter.onTaskBegin) === null || _b === void 0 ? void 0 : _b.call(reporter, task, ctx));
16
- if (task.mode === 'run') {
17
- try {
18
- await callHook(task.suite, 'beforeEach', [task, task.suite]);
19
- await task.fn();
20
- task.state = 'pass';
21
- }
22
- catch (e) {
23
- task.state = 'fail';
24
- task.error = e;
25
- process.exitCode = 1;
26
- }
27
- try {
28
- await callHook(task.suite, 'afterEach', [task, task.suite]);
29
- }
30
- catch (e) {
31
- task.state = 'fail';
32
- task.error = e;
33
- process.exitCode = 1;
34
- }
35
- }
36
- await ((_c = reporter.onTaskEnd) === null || _c === void 0 ? void 0 : _c.call(reporter, task, ctx));
37
- }
38
- export async function collectFiles(paths) {
39
- const files = {};
40
- for (const filepath of paths) {
41
- const file = {
42
- filepath,
43
- suites: [],
44
- collected: false,
45
- };
46
- clearContext();
47
- try {
48
- await import(filepath);
49
- const collectors = [defaultSuite, ...context.suites];
50
- for (const c of collectors) {
51
- context.currentSuite = c;
52
- file.suites.push(await c.collect(file));
53
- }
54
- file.collected = true;
55
- }
56
- catch (e) {
57
- file.error = e;
58
- file.collected = false;
59
- process.exitCode = 1;
60
- }
61
- files[filepath] = file;
62
- }
63
- const allFiles = Object.values(files);
64
- const allSuites = allFiles.reduce((suites, file) => suites.concat(file.suites), []);
65
- interpretOnlyMode(allSuites);
66
- allSuites.forEach((i) => {
67
- if (i.mode === 'skip')
68
- i.tasks.forEach(t => t.mode === 'run' && (t.mode = 'skip'));
69
- else
70
- interpretOnlyMode(i.tasks);
71
- i.tasks.forEach(t => t.mode === 'skip' && (t.state = 'skip'));
72
- });
73
- return files;
74
- }
75
- /**
76
- * If any items been marked as `only`, mark all other items as `skip`.
77
- */
78
- function interpretOnlyMode(items) {
79
- if (items.some(i => i.mode === 'only')) {
80
- items.forEach((i) => {
81
- if (i.mode === 'run')
82
- i.mode = 'skip';
83
- else if (i.mode === 'only')
84
- i.mode = 'run';
85
- });
86
- }
87
- }
88
- export async function runSuite(suite, ctx) {
89
- var _a, _b;
90
- const { reporter } = ctx;
91
- await ((_a = reporter.onSuiteBegin) === null || _a === void 0 ? void 0 : _a.call(reporter, suite, ctx));
92
- if (suite.mode === 'skip') {
93
- suite.status = 'skip';
94
- }
95
- else if (suite.mode === 'todo') {
96
- suite.status = 'todo';
97
- }
98
- else {
99
- try {
100
- await callHook(suite, 'beforeAll', [suite]);
101
- for (const t of suite.tasks)
102
- await runTask(t, ctx);
103
- await callHook(suite, 'afterAll', [suite]);
104
- }
105
- catch (e) {
106
- suite.error = e;
107
- suite.status = 'fail';
108
- process.exitCode = 1;
109
- }
110
- }
111
- await ((_b = reporter.onSuiteEnd) === null || _b === void 0 ? void 0 : _b.call(reporter, suite, ctx));
112
- }
113
- export async function runFile(file, ctx) {
114
- var _a, _b;
115
- const { reporter } = ctx;
116
- const runnableSuites = file.suites.filter(i => i.mode === 'run');
117
- if (runnableSuites.length === 0)
118
- return;
119
- await ((_a = reporter.onFileBegin) === null || _a === void 0 ? void 0 : _a.call(reporter, file, ctx));
120
- if (ctx.config.parallel) {
121
- await Promise.all(file.suites.map(suite => runSuite(suite, ctx)));
122
- }
123
- else {
124
- for (const suite of file.suites)
125
- await runSuite(suite, ctx);
126
- }
127
- await ((_b = reporter.onFileEnd) === null || _b === void 0 ? void 0 : _b.call(reporter, file, ctx));
128
- }
129
- export async function runFiles(filesMap, ctx) {
130
- var _a;
131
- const { reporter } = ctx;
132
- await ((_a = reporter.onCollected) === null || _a === void 0 ? void 0 : _a.call(reporter, Object.values(filesMap), ctx));
133
- for (const file of Object.values(filesMap))
134
- await runFile(file, ctx);
135
- }
136
- export async function run(config) {
137
- var _a, _b, _c;
138
- config.reporter = config.reporter || new DefaultReporter();
139
- const { reporter } = config;
140
- // if watch, tell `vite-node` not to end the process
141
- if (config.watch)
142
- process.__vite_node__.watch = true;
143
- // setup chai
144
- await setupChai(config);
145
- // collect files
146
- let testFilepaths = await fg(config.includes || defaultIncludes, {
147
- absolute: true,
148
- cwd: config.root,
149
- ignore: config.excludes || defaultExcludes,
150
- });
151
- // if name filters are provided by the CLI
152
- if ((_a = config.filters) === null || _a === void 0 ? void 0 : _a.length)
153
- testFilepaths = testFilepaths.filter(i => config.filters.some(f => i.includes(f)));
154
- if (!testFilepaths.length) {
155
- console.error('No test files found');
156
- process.exitCode = 1;
157
- return;
158
- }
159
- // setup envs
160
- if (config.global)
161
- (await import('../integrations/global')).registerApiGlobally();
162
- if (config.jsdom)
163
- (await import('../integrations/jsdom')).setupJSDOM(globalThis);
164
- await ((_b = reporter.onStart) === null || _b === void 0 ? void 0 : _b.call(reporter, config));
165
- const filesMap = await collectFiles(testFilepaths);
166
- const snapshotManager = getSnapshotManager();
167
- const ctx = {
168
- filesMap,
169
- get files() {
170
- return Object.values(this.filesMap);
171
- },
172
- get suites() {
173
- return Object.values(this.filesMap)
174
- .reduce((suites, file) => suites.concat(file.suites), []);
175
- },
176
- get tasks() {
177
- return this.suites
178
- .reduce((tasks, suite) => tasks.concat(suite.tasks), []);
179
- },
180
- config,
181
- reporter,
182
- snapshotManager,
183
- };
184
- await runFiles(filesMap, ctx);
185
- snapshotManager.saveSnap();
186
- await ((_c = reporter.onFinished) === null || _c === void 0 ? void 0 : _c.call(reporter, ctx));
187
- if (config.watch)
188
- await startWatcher(ctx);
189
- }
190
- export async function startWatcher(ctx) {
191
- var _a;
192
- const { reporter, snapshotManager, filesMap } = ctx;
193
- await ((_a = reporter.onWatcherStart) === null || _a === void 0 ? void 0 : _a.call(reporter, ctx));
194
- let timer;
195
- const changedTests = new Set();
196
- const seen = new Set();
197
- const { server, moduleCache } = process.__vite_node__;
198
- server.watcher.on('change', async (id) => {
199
- id = normalizePath(id);
200
- getDependencyTests(id, ctx, changedTests, seen);
201
- seen.forEach(i => moduleCache.delete(i));
202
- seen.clear();
203
- if (changedTests.size === 0)
204
- return;
205
- clearTimeout(timer);
206
- timer = setTimeout(async () => {
207
- var _a, _b, _c;
208
- if (changedTests.size === 0)
209
- return;
210
- snapshotManager.clear();
211
- const paths = Array.from(changedTests);
212
- changedTests.clear();
213
- await ((_a = reporter.onWatcherRerun) === null || _a === void 0 ? void 0 : _a.call(reporter, paths, id, ctx));
214
- paths.forEach(i => moduleCache.delete(i));
215
- const newFilesMap = await collectFiles(paths);
216
- Object.assign(filesMap, newFilesMap);
217
- await runFiles(newFilesMap, ctx);
218
- snapshotManager.saveSnap();
219
- await ((_b = reporter.onFinished) === null || _b === void 0 ? void 0 : _b.call(reporter, ctx, Object.values(newFilesMap)));
220
- await ((_c = reporter.onWatcherStart) === null || _c === void 0 ? void 0 : _c.call(reporter, ctx));
221
- }, 100);
222
- });
223
- // add an empty promise so it never resolves
224
- await new Promise(() => { });
225
- }
226
- function normalizePath(path) {
227
- const normalized = path.replace(/\\/g, '/');
228
- if (normalized.startsWith('/'))
229
- return normalized;
230
- return `/${normalized}`;
231
- }
232
- function getDependencyTests(id, ctx, set = new Set(), seen = new Set()) {
233
- if (seen.has(id) || set.has(id))
234
- return set;
235
- seen.add(id);
236
- if (id in ctx.filesMap) {
237
- set.add(id);
238
- return set;
239
- }
240
- const mod = process.__vite_node__.server.moduleGraph.getModuleById(id);
241
- if (mod) {
242
- mod.importers.forEach((i) => {
243
- if (i.id)
244
- getDependencyTests(i.id, ctx, set, seen);
245
- });
246
- }
247
- return set;
248
- }
package/dist/suite.d.ts DELETED
@@ -1,26 +0,0 @@
1
- import { SuiteCollector, TestFactory, TestFunction, Suite } from './types';
2
- export declare const defaultSuite: SuiteCollector;
3
- export declare const test: {
4
- (name: string, fn: TestFunction): void;
5
- skip(name: string, fn: TestFunction): void;
6
- only(name: string, fn: TestFunction): void;
7
- todo(name: string): void;
8
- };
9
- export declare function suite(suiteName: string, factory?: TestFactory): SuiteCollector;
10
- export declare namespace suite {
11
- var skip: (suiteName: string, factory?: TestFactory | undefined) => SuiteCollector;
12
- var only: (suiteName: string, factory?: TestFactory | undefined) => SuiteCollector;
13
- var todo: (suiteName: string) => SuiteCollector;
14
- }
15
- export declare const describe: typeof suite;
16
- export declare const it: {
17
- (name: string, fn: TestFunction): void;
18
- skip(name: string, fn: TestFunction): void;
19
- only(name: string, fn: TestFunction): void;
20
- todo(name: string): void;
21
- };
22
- export declare const beforeAll: (fn: Suite['hooks']['beforeAll'][0]) => void;
23
- export declare const afterAll: (fn: Suite['hooks']['afterAll'][0]) => void;
24
- export declare const beforeEach: (fn: Suite['hooks']['beforeEach'][0]) => void;
25
- export declare const afterEach: (fn: Suite['hooks']['afterEach'][0]) => void;
26
- export declare function clearContext(): void;