vitest 0.0.0 → 0.0.4

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 (40) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +57 -0
  3. package/bin/vitest.mjs +39 -0
  4. package/dist/chai.d.ts +12 -0
  5. package/dist/chai.js +1 -0
  6. package/dist/cli.d.ts +1 -0
  7. package/dist/cli.js +28 -0
  8. package/dist/config.d.ts +17 -0
  9. package/dist/config.js +3 -0
  10. package/dist/context.d.ts +2 -0
  11. package/dist/context.js +4 -0
  12. package/dist/hooks.d.ts +50 -0
  13. package/dist/hooks.js +17 -0
  14. package/dist/index.d.ts +4 -0
  15. package/dist/index.js +4 -0
  16. package/dist/run.d.ts +5 -0
  17. package/dist/run.js +94 -0
  18. package/dist/snapshot/index.d.ts +9 -0
  19. package/dist/snapshot/index.js +39 -0
  20. package/dist/snapshot/manager.d.ts +27 -0
  21. package/dist/snapshot/manager.js +67 -0
  22. package/dist/snapshot/utils/SnapshotResult.d.ts +0 -0
  23. package/dist/snapshot/utils/SnapshotResult.js +1 -0
  24. package/dist/snapshot/utils/jest-config-helper.d.ts +3 -0
  25. package/dist/snapshot/utils/jest-config-helper.js +39 -0
  26. package/dist/snapshot/utils/jest-reporters-lite.d.ts +2 -0
  27. package/dist/snapshot/utils/jest-reporters-lite.js +71 -0
  28. package/dist/snapshot/utils/jest-test-result-helper.d.ts +6 -0
  29. package/dist/snapshot/utils/jest-test-result-helper.js +65 -0
  30. package/dist/snapshot/utils/tyoes.d.ts +0 -0
  31. package/dist/snapshot/utils/tyoes.js +1 -0
  32. package/dist/snapshot/utils/types.d.ts +29 -0
  33. package/dist/snapshot/utils/types.js +1 -0
  34. package/dist/suite.d.ts +7 -0
  35. package/dist/suite.js +41 -0
  36. package/dist/types.d.ts +33 -0
  37. package/dist/types.js +2 -0
  38. package/dist/utils/hook.d.ts +5 -0
  39. package/dist/utils/hook.js +14 -0
  40. package/package.json +63 -3
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2021 Anthony Fu <https://github.com/antfu>
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,57 @@
1
+ # vitest
2
+
3
+ [![NPM version](https://img.shields.io/npm/v/vitest?color=a1b858&label=)](https://www.npmjs.com/package/vitest)
4
+
5
+ A blazing fast test runner powered by Vite.
6
+
7
+ ## Features
8
+
9
+ - Vite's transformer, resolver, and plugin system. Powered by [vite-node](https://github.com/antfu/vite-node).
10
+ - Jest Snapshot.
11
+ - Chai for assertions.
12
+ - Async suite / test.
13
+ - ESM friendly, top level await.
14
+
15
+ ```ts
16
+ import { it, describe, expect, assert } from 'vitest'
17
+
18
+ describe('suite name', () => {
19
+ it('foo', () => {
20
+ assert.equal(Math.sqrt(4), 2)
21
+ })
22
+
23
+ it('bar', () => {
24
+ expect(1 + 1).eq(2)
25
+ })
26
+
27
+ it('snapshot', () => {
28
+ expect({ foo: 'bar' }).toMatchSnapshot()
29
+ })
30
+ })
31
+ ```
32
+
33
+ ```bash
34
+ $ npx vitest
35
+ ```
36
+
37
+ ## TODO
38
+
39
+ - [ ] Reporter & Better output
40
+ - [ ] CLI Help
41
+ - [ ] Task filter
42
+ - [ ] Mock
43
+ - [ ] JSDom
44
+ - [ ] Watch
45
+ - [ ] Coverage
46
+
47
+ ## Sponsors
48
+
49
+ <p align="center">
50
+ <a href="https://cdn.jsdelivr.net/gh/antfu/static/sponsors.svg">
51
+ <img src='https://cdn.jsdelivr.net/gh/antfu/static/sponsors.svg'/>
52
+ </a>
53
+ </p>
54
+
55
+ ## License
56
+
57
+ [MIT](./LICENSE) License © 2021 [Anthony Fu](https://github.com/antfu)
package/bin/vitest.mjs ADDED
@@ -0,0 +1,39 @@
1
+ #!/usr/bin/env node
2
+ 'use strict'
3
+
4
+ import { fileURLToPath } from 'url'
5
+ import { resolve, dirname } from 'path'
6
+ import { run } from 'vite-node'
7
+ import minimist from 'minimist'
8
+
9
+ const argv = minimist(process.argv.slice(2), {
10
+ alias: {
11
+ c: 'config',
12
+ },
13
+ string: ['root', 'config'],
14
+ boolean: ['dev'],
15
+ })
16
+
17
+ const __dirname = dirname(fileURLToPath(import.meta.url))
18
+ const root = resolve(argv.root || process.cwd())
19
+
20
+ await run({
21
+ root,
22
+ files: [
23
+ resolve(__dirname, argv.dev ? '../src/cli.ts' : '../dist/cli.js'),
24
+ ],
25
+ config: resolve(root, argv.config || 'vitest.config.ts'),
26
+ defaultConfig: {
27
+ optimizeDeps: {
28
+ exclude: [
29
+ 'vitest',
30
+ ],
31
+ },
32
+ },
33
+ shouldExternalize(id) {
34
+ if (id.includes('/node_modules/vitest/'))
35
+ return false
36
+ else
37
+ return id.includes('/node_modules/')
38
+ },
39
+ })
package/dist/chai.d.ts ADDED
@@ -0,0 +1,12 @@
1
+ export { assert, should, expect } from 'chai';
2
+ declare global {
3
+ namespace Chai {
4
+ interface Assertion {
5
+ toMatchSnapshot(message?: string): Assertion;
6
+ matchSnapshot(message?: string): Assertion;
7
+ }
8
+ interface ExpectStatic {
9
+ addSnapshotSerializer: import('pretty-format').Plugin;
10
+ }
11
+ }
12
+ }
package/dist/chai.js ADDED
@@ -0,0 +1 @@
1
+ export { assert, should, expect } from 'chai';
package/dist/cli.d.ts ADDED
@@ -0,0 +1 @@
1
+ export {};
package/dist/cli.js ADDED
@@ -0,0 +1,28 @@
1
+ var _a;
2
+ import minimist from 'minimist';
3
+ import c from 'picocolors';
4
+ import { run } from './run';
5
+ const { log } = console;
6
+ const argv = minimist(process.argv.slice(2), {
7
+ alias: {
8
+ u: 'update',
9
+ },
10
+ string: ['root', 'config'],
11
+ boolean: ['update', 'dev'],
12
+ unknown(name) {
13
+ if (name[0] === '-') {
14
+ console.error(c.red(`Unknown argument: ${name}`));
15
+ help();
16
+ process.exit(1);
17
+ }
18
+ return true;
19
+ },
20
+ });
21
+ // @ts-expect-error
22
+ const server = (_a = process === null || process === void 0 ? void 0 : process.__vite_node__) === null || _a === void 0 ? void 0 : _a.server;
23
+ const viteConfig = (server === null || server === void 0 ? void 0 : server.config) || {};
24
+ const testOptions = viteConfig.test || {};
25
+ await run(Object.assign(Object.assign({}, testOptions), { updateSnapshot: argv.update, rootDir: argv.root || process.cwd() }));
26
+ function help() {
27
+ log('Help: finish help');
28
+ }
@@ -0,0 +1,17 @@
1
+ import { UserConfig } from 'vite';
2
+ import { UserOptions } from './types';
3
+ export interface VitestConfig extends UserConfig {
4
+ /**
5
+ * Options for Vitest
6
+ */
7
+ test?: UserOptions;
8
+ }
9
+ export declare function defineConfig(config: VitestConfig): VitestConfig;
10
+ declare module 'vite' {
11
+ interface UserConfig {
12
+ /**
13
+ * Options for Vitest
14
+ */
15
+ test?: UserOptions;
16
+ }
17
+ }
package/dist/config.js ADDED
@@ -0,0 +1,3 @@
1
+ export function defineConfig(config) {
2
+ return config;
3
+ }
@@ -0,0 +1,2 @@
1
+ import { GlobalContext } from './types';
2
+ export declare const context: GlobalContext;
@@ -0,0 +1,4 @@
1
+ export const context = {
2
+ suites: [],
3
+ currentSuite: null,
4
+ };
@@ -0,0 +1,50 @@
1
+ import { Suite, Task } from './types';
2
+ import { TaskResult } from '.';
3
+ export declare const beforeHook: {
4
+ on(fn: (...args: any[]) => void | Promise<void>): void;
5
+ fire(...args: any[]): Promise<void>;
6
+ clear(): void;
7
+ };
8
+ export declare const afterHook: {
9
+ on(fn: (...args: any[]) => void | Promise<void>): void;
10
+ fire(...args: any[]): Promise<void>;
11
+ clear(): void;
12
+ };
13
+ export declare const beforeEachHook: {
14
+ on(fn: (args_0: Task) => void | Promise<void>): void;
15
+ fire(args_0: Task): Promise<void>;
16
+ clear(): void;
17
+ };
18
+ export declare const afterEachHook: {
19
+ on(fn: (args_0: Task, args_1: TaskResult) => void | Promise<void>): void;
20
+ fire(args_0: Task, args_1: TaskResult): Promise<void>;
21
+ clear(): void;
22
+ };
23
+ export declare const beforeFileHook: {
24
+ on(fn: (args_0: string) => void | Promise<void>): void;
25
+ fire(args_0: string): Promise<void>;
26
+ clear(): void;
27
+ };
28
+ export declare const afterFileHook: {
29
+ on(fn: (args_0: string) => void | Promise<void>): void;
30
+ fire(args_0: string): Promise<void>;
31
+ clear(): void;
32
+ };
33
+ export declare const beforeSuiteHook: {
34
+ on(fn: (args_0: Suite) => void | Promise<void>): void;
35
+ fire(args_0: Suite): Promise<void>;
36
+ clear(): void;
37
+ };
38
+ export declare const afterSuiteHook: {
39
+ on(fn: (args_0: Suite) => void | Promise<void>): void;
40
+ fire(args_0: Suite): Promise<void>;
41
+ clear(): void;
42
+ };
43
+ export declare const before: (fn: (...args: any[]) => void | Promise<void>) => void;
44
+ export declare const after: (fn: (...args: any[]) => void | Promise<void>) => void;
45
+ export declare const beforeEach: (fn: (args_0: Task) => void | Promise<void>) => void;
46
+ export declare const afterEach: (fn: (args_0: Task, args_1: TaskResult) => void | Promise<void>) => void;
47
+ export declare const beforeFile: (fn: (args_0: string) => void | Promise<void>) => void;
48
+ export declare const afterFile: (fn: (args_0: string) => void | Promise<void>) => void;
49
+ export declare const beforeSuite: (fn: (args_0: Suite) => void | Promise<void>) => void;
50
+ export declare const afterSuite: (fn: (args_0: Suite) => void | Promise<void>) => void;
package/dist/hooks.js ADDED
@@ -0,0 +1,17 @@
1
+ import { createHook } from './utils/hook';
2
+ export const beforeHook = createHook();
3
+ export const afterHook = createHook();
4
+ export const beforeEachHook = createHook();
5
+ export const afterEachHook = createHook();
6
+ export const beforeFileHook = createHook();
7
+ export const afterFileHook = createHook();
8
+ export const beforeSuiteHook = createHook();
9
+ export const afterSuiteHook = createHook();
10
+ export const before = beforeHook.on;
11
+ export const after = afterHook.on;
12
+ export const beforeEach = beforeEachHook.on;
13
+ export const afterEach = afterEachHook.on;
14
+ export const beforeFile = beforeFileHook.on;
15
+ export const afterFile = afterFileHook.on;
16
+ export const beforeSuite = beforeSuiteHook.on;
17
+ export const afterSuite = afterSuiteHook.on;
@@ -0,0 +1,4 @@
1
+ export * from './types';
2
+ export * from './suite';
3
+ export * from './config';
4
+ export * from './chai';
package/dist/index.js ADDED
@@ -0,0 +1,4 @@
1
+ export * from './types';
2
+ export * from './suite';
3
+ export * from './config';
4
+ export * from './chai';
package/dist/run.d.ts ADDED
@@ -0,0 +1,5 @@
1
+ import { File, Options, Task, TaskResult } from './types';
2
+ export declare function runTasks(tasks: Task[]): Promise<TaskResult[]>;
3
+ export declare function parseFile(filepath: string): Promise<File>;
4
+ export declare function runFile(filepath: string): Promise<void>;
5
+ export declare function run(options?: Options): Promise<void>;
package/dist/run.js ADDED
@@ -0,0 +1,94 @@
1
+ import { relative } from 'path';
2
+ import c from 'picocolors';
3
+ import chai from 'chai';
4
+ import fg from 'fast-glob';
5
+ import { clearContext, defaultSuite } from './suite';
6
+ import { context } from './context';
7
+ import { afterEachHook, afterFileHook, afterHook, afterSuiteHook, beforeEachHook, beforeFileHook, beforeHook, beforeSuiteHook } from './hooks';
8
+ import { SnapshotPlugin } from './snapshot/index';
9
+ export async function runTasks(tasks) {
10
+ const results = [];
11
+ for (const task of tasks) {
12
+ const result = { task };
13
+ await beforeEachHook.fire(task);
14
+ try {
15
+ await task.fn();
16
+ }
17
+ catch (e) {
18
+ result.error = e;
19
+ }
20
+ results.push(result);
21
+ await afterEachHook.fire(task, result);
22
+ }
23
+ return results;
24
+ }
25
+ // TODO: REPORTER
26
+ const { log } = console;
27
+ export async function parseFile(filepath) {
28
+ clearContext();
29
+ await import(filepath);
30
+ const suites = [defaultSuite, ...context.suites];
31
+ const tasks = await Promise.all(suites.map(async (suite) => {
32
+ await beforeSuiteHook.fire(suite);
33
+ context.currentSuite = suite;
34
+ return [suite, await suite.collect()];
35
+ }));
36
+ const file = {
37
+ filepath,
38
+ suites,
39
+ tasks,
40
+ };
41
+ file.tasks.forEach(([, tasks]) => tasks.forEach(task => task.file = file));
42
+ return file;
43
+ }
44
+ export async function runFile(filepath) {
45
+ await beforeFileHook.fire(filepath);
46
+ const file = await parseFile(filepath);
47
+ for (const [suite, tasks] of file.tasks) {
48
+ let indent = 1;
49
+ if (suite.name) {
50
+ log(' '.repeat(indent * 2) + suite.name);
51
+ indent += 1;
52
+ }
53
+ const result = await runTasks(tasks);
54
+ for (const r of result) {
55
+ if (r.error === undefined) {
56
+ log(`${' '.repeat(indent * 2)}${c.inverse(c.green(' PASS '))} ${c.green(r.task.name)}`);
57
+ }
58
+ else {
59
+ console.error(`${' '.repeat(indent * 2)}${c.inverse(c.red(' FAIL '))} ${c.red(r.task.name)}`);
60
+ console.error(' '.repeat((indent + 2) * 2) + c.red(String(r.error)));
61
+ process.exitCode = 1;
62
+ }
63
+ }
64
+ if (suite.name)
65
+ indent -= 1;
66
+ await afterSuiteHook.fire(suite);
67
+ }
68
+ await afterFileHook.fire(filepath);
69
+ }
70
+ export async function run(options = {}) {
71
+ const { rootDir = process.cwd() } = options;
72
+ chai.use(SnapshotPlugin({
73
+ rootDir,
74
+ update: options.updateSnapshot,
75
+ }));
76
+ const files = await fg(options.includes || ['**/*.{test,spec}.{js,mjs,cjs,ts,mts,cts,jsx,tsx}'], {
77
+ absolute: true,
78
+ cwd: options.rootDir,
79
+ ignore: options.excludes || ['/node_modules/', '/dist/'],
80
+ });
81
+ if (!files.length) {
82
+ console.error('No test files found');
83
+ process.exitCode = 1;
84
+ return;
85
+ }
86
+ await beforeHook.fire();
87
+ for (const file of files) {
88
+ log(`${relative(process.cwd(), file)}`);
89
+ await runFile(file);
90
+ log();
91
+ }
92
+ await afterHook.fire();
93
+ log();
94
+ }
@@ -0,0 +1,9 @@
1
+ import { use as chaiUse } from 'chai';
2
+ declare type FirstFunctionArgument<T> = T extends (arg: infer A) => unknown ? A : never;
3
+ declare type ChaiPlugin = FirstFunctionArgument<typeof chaiUse>;
4
+ export interface SnapshotOptions {
5
+ rootDir: string;
6
+ update?: boolean;
7
+ }
8
+ export declare function SnapshotPlugin(options: SnapshotOptions): ChaiPlugin;
9
+ export {};
@@ -0,0 +1,39 @@
1
+ import Snap from 'jest-snapshot';
2
+ import { after, before, beforeEach } from '../hooks';
3
+ import { SnapshotManager } from './manager';
4
+ const { addSerializer } = Snap;
5
+ let _manager;
6
+ export function SnapshotPlugin(options) {
7
+ const { rootDir } = options;
8
+ _manager = new SnapshotManager({
9
+ rootDir,
10
+ update: options.update,
11
+ });
12
+ return function (chai, utils) {
13
+ before(async () => {
14
+ _manager.snapshotResolver = await Snap.buildSnapshotResolver({
15
+ transform: [],
16
+ rootDir,
17
+ });
18
+ });
19
+ beforeEach((task) => {
20
+ var _a;
21
+ _manager.setContext({
22
+ file: ((_a = task.file) === null || _a === void 0 ? void 0 : _a.filepath) || task.name,
23
+ title: task.name,
24
+ fullTitle: [task.suite.name, task.name].filter(Boolean).join(' > '),
25
+ });
26
+ });
27
+ after(() => {
28
+ _manager.saveSnap();
29
+ _manager.report();
30
+ });
31
+ for (const key of ['matchSnapshot', 'toMatchSnapshot']) {
32
+ utils.addMethod(chai.Assertion.prototype, key, function (message) {
33
+ const expected = utils.flag(this, 'object');
34
+ _manager.assert(expected, message);
35
+ });
36
+ }
37
+ chai.expect.addSnapshotSerializer = addSerializer;
38
+ };
39
+ }
@@ -0,0 +1,27 @@
1
+ import type { SnapshotStateType, SnapshotResolver } from 'jest-snapshot';
2
+ import type { SnapshotStateOptions } from 'jest-snapshot/build/State';
3
+ import { SnapshotSummary } from './utils/types';
4
+ export interface Context {
5
+ file: string;
6
+ title?: string;
7
+ fullTitle?: string;
8
+ }
9
+ export declare class SnapshotManager {
10
+ snapshotState: SnapshotStateType | null;
11
+ snapshotSummary: SnapshotSummary;
12
+ snapshotOptions: SnapshotStateOptions;
13
+ context: Context | null;
14
+ testFile: string;
15
+ snapshotResolver: SnapshotResolver | null;
16
+ rootDir: string;
17
+ constructor({ rootDir, update, snapshotResolver, }: {
18
+ rootDir: string;
19
+ update?: boolean;
20
+ snapshotResolver?: SnapshotResolver | null;
21
+ });
22
+ onFileChanged(): void;
23
+ setContext(context: Context): void;
24
+ assert(received: unknown, message: string): void;
25
+ saveSnap(): void;
26
+ report(): void;
27
+ }
@@ -0,0 +1,67 @@
1
+ import chai from 'chai';
2
+ import Snap from 'jest-snapshot';
3
+ import { packSnapshotState, addSnapshotResult, makeEmptySnapshotSummary, } from './utils/jest-test-result-helper';
4
+ import { getSnapshotSummaryOutput } from './utils/jest-reporters-lite';
5
+ const { expect } = chai;
6
+ const { SnapshotState } = Snap;
7
+ export class SnapshotManager {
8
+ constructor({ rootDir, update, snapshotResolver = null, }) {
9
+ this.snapshotState = null;
10
+ this.context = null;
11
+ this.testFile = '';
12
+ this.rootDir = rootDir;
13
+ this.snapshotResolver = snapshotResolver;
14
+ const env = process.env;
15
+ const CI = !!env.CI;
16
+ const UPDATE_SNAPSHOT = update || env.UPDATE_SNAPSHOT;
17
+ this.snapshotOptions = {
18
+ updateSnapshot: CI && !UPDATE_SNAPSHOT
19
+ ? 'none'
20
+ : UPDATE_SNAPSHOT
21
+ ? 'all'
22
+ : 'new',
23
+ };
24
+ this.snapshotSummary = makeEmptySnapshotSummary(this.snapshotOptions);
25
+ }
26
+ onFileChanged() {
27
+ if (!this.context)
28
+ return;
29
+ if (this.snapshotState !== null)
30
+ this.saveSnap();
31
+ this.testFile = this.context.file;
32
+ this.snapshotState = new SnapshotState(this.snapshotResolver.resolveSnapshotPath(this.testFile), this.snapshotOptions);
33
+ }
34
+ setContext(context) {
35
+ if (!context.title || !context.file)
36
+ return;
37
+ this.context = context;
38
+ if (this.testFile !== context.file)
39
+ this.onFileChanged();
40
+ }
41
+ assert(received, message) {
42
+ if (!this.snapshotState || !this.context)
43
+ return;
44
+ const { actual, expected, key, pass } = this.snapshotState.match({
45
+ testName: this.context.fullTitle || this.context.title || this.context.file,
46
+ received,
47
+ isInline: false,
48
+ });
49
+ if (!pass) {
50
+ expect(actual.trim()).equals(expected ? expected.trim() : '', message || `Snapshot name: \`${key}\``);
51
+ }
52
+ }
53
+ saveSnap() {
54
+ if (!this.testFile || !this.snapshotState)
55
+ return;
56
+ const packedSnapshotState = packSnapshotState(this.snapshotState);
57
+ addSnapshotResult(this.snapshotSummary, packedSnapshotState, this.testFile);
58
+ this.testFile = '';
59
+ this.snapshotState = null;
60
+ }
61
+ report() {
62
+ const outputs = getSnapshotSummaryOutput(this.rootDir, this.snapshotSummary);
63
+ if (outputs.length > 1)
64
+ // eslint-disable-next-line no-console
65
+ console.log(`\n${outputs.join('\n')}`);
66
+ }
67
+ }
File without changes
@@ -0,0 +1 @@
1
+ "use strict";
@@ -0,0 +1,3 @@
1
+ export declare const replaceRootDirInPath: (rootDir: string, filePath: string) => string;
2
+ export declare function replaceRootDirInObject<T>(rootDir: string, config: T): T;
3
+ export declare function _replaceRootDirTags<T>(rootDir: string, config: T): T;
@@ -0,0 +1,39 @@
1
+ /**
2
+ * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
3
+ *
4
+ * This source code is licensed under the MIT license found in the
5
+ * LICENSE file in the root directory of this source tree.
6
+ */
7
+ import path from 'path';
8
+ export const replaceRootDirInPath = (rootDir, filePath) => {
9
+ if (!/^<rootDir>/.test(filePath))
10
+ return filePath;
11
+ return path.resolve(rootDir, path.normalize(`./${filePath.substr('<rootDir>'.length)}`));
12
+ };
13
+ export function replaceRootDirInObject(rootDir, config) {
14
+ const newConfig = {};
15
+ for (const configKey of Object.keys(config)) {
16
+ newConfig[configKey]
17
+ = configKey === 'rootDir'
18
+ ? config[configKey]
19
+ : _replaceRootDirTags(rootDir, config[configKey]);
20
+ }
21
+ return newConfig;
22
+ }
23
+ export function _replaceRootDirTags(rootDir, config) {
24
+ if (config == null)
25
+ return config;
26
+ switch (typeof config) {
27
+ case 'object':
28
+ if (Array.isArray(config)) {
29
+ /// can be string[] or {}[]
30
+ return config.map(item => _replaceRootDirTags(rootDir, item));
31
+ }
32
+ if (config instanceof RegExp)
33
+ return config;
34
+ return replaceRootDirInObject(rootDir, config);
35
+ case 'string':
36
+ return replaceRootDirInPath(rootDir, config);
37
+ }
38
+ return config;
39
+ }
@@ -0,0 +1,2 @@
1
+ import { SnapshotSummary } from './types';
2
+ export declare const getSnapshotSummaryOutput: (rootDir: string, snapshots: SnapshotSummary) => Array<string>;
@@ -0,0 +1,71 @@
1
+ /**
2
+ * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
3
+ *
4
+ * This source code is licensed under the MIT license found in the
5
+ * LICENSE file in the root directory of this source tree.
6
+ */
7
+ import path, { isAbsolute } from 'path';
8
+ import { pluralize } from 'jest-util';
9
+ import slash from 'slash';
10
+ import c from 'picocolors';
11
+ const formatTestPath = (rootDir, testPath) => {
12
+ if (isAbsolute(testPath))
13
+ testPath = path.relative(rootDir, testPath);
14
+ const dirname = path.dirname(testPath);
15
+ const basename = path.basename(testPath);
16
+ return slash(c.dim(dirname + path.sep) + c.bold(basename));
17
+ };
18
+ const ARROW = ' \u203A ';
19
+ const DOWN_ARROW = ' \u21B3 ';
20
+ const DOT = ' \u2022 ';
21
+ const FAIL_COLOR = (v) => c.bold(c.red(v));
22
+ const OBSOLETE_COLOR = (v) => c.bold(c.yellow(v));
23
+ const SNAPSHOT_ADDED = (v) => c.bold(c.green(v));
24
+ const SNAPSHOT_NOTE = c.dim;
25
+ const SNAPSHOT_REMOVED = (v) => c.bold(c.green(v));
26
+ const SNAPSHOT_SUMMARY = c.bold;
27
+ const SNAPSHOT_UPDATED = (v) => c.bold(c.green(v));
28
+ const updateCommand = 're-run mocha with `--update` to update them';
29
+ export const getSnapshotSummaryOutput = (rootDir, snapshots) => {
30
+ const summary = [];
31
+ summary.push(SNAPSHOT_SUMMARY('Snapshot Summary'));
32
+ if (snapshots.added) {
33
+ summary.push(`${SNAPSHOT_ADDED(`${ARROW + pluralize('snapshot', snapshots.added)} written `)}from ${pluralize('test suite', snapshots.filesAdded)}.`);
34
+ }
35
+ if (snapshots.unmatched) {
36
+ summary.push(`${FAIL_COLOR(`${ARROW}${pluralize('snapshot', snapshots.unmatched)} failed`)} from ${pluralize('test suite', snapshots.filesUnmatched)}. ${SNAPSHOT_NOTE(`Inspect your code changes or ${updateCommand} to update them.`)}`);
37
+ }
38
+ if (snapshots.updated) {
39
+ summary.push(`${SNAPSHOT_UPDATED(`${ARROW + pluralize('snapshot', snapshots.updated)} updated `)}from ${pluralize('test suite', snapshots.filesUpdated)}.`);
40
+ }
41
+ if (snapshots.filesRemoved) {
42
+ if (snapshots.didUpdate) {
43
+ summary.push(`${SNAPSHOT_REMOVED(`${ARROW}${pluralize('snapshot file', snapshots.filesRemoved)} removed `)}from ${pluralize('test suite', snapshots.filesRemoved)}.`);
44
+ }
45
+ else {
46
+ summary.push(`${OBSOLETE_COLOR(`${ARROW}${pluralize('snapshot file', snapshots.filesRemoved)} obsolete `)}from ${pluralize('test suite', snapshots.filesRemoved)}. ${SNAPSHOT_NOTE(`To remove ${snapshots.filesRemoved === 1 ? 'it' : 'them all'}, ${updateCommand}.`)}`);
47
+ }
48
+ }
49
+ if (snapshots.filesRemovedList && snapshots.filesRemovedList.length) {
50
+ const [head, ...tail] = snapshots.filesRemovedList;
51
+ summary.push(` ${DOWN_ARROW} ${DOT}${formatTestPath(rootDir, head)}`);
52
+ tail.forEach((key) => {
53
+ summary.push(` ${DOT}${formatTestPath(rootDir, key)}`);
54
+ });
55
+ }
56
+ if (snapshots.unchecked) {
57
+ if (snapshots.didUpdate) {
58
+ summary.push(`${SNAPSHOT_REMOVED(`${ARROW}${pluralize('snapshot', snapshots.unchecked)} removed `)}from ${pluralize('test suite', snapshots.uncheckedKeysByFile.length)}.`);
59
+ }
60
+ else {
61
+ summary.push(`${OBSOLETE_COLOR(`${ARROW}${pluralize('snapshot', snapshots.unchecked)} obsolete `)}from ${pluralize('test suite', snapshots.uncheckedKeysByFile.length)}. ${SNAPSHOT_NOTE(`To remove ${snapshots.unchecked === 1 ? 'it' : 'them all'}, ${updateCommand}.`)}`);
62
+ }
63
+ snapshots.uncheckedKeysByFile.forEach((uncheckedFile) => {
64
+ summary.push(` ${DOWN_ARROW}${formatTestPath(rootDir, uncheckedFile.filePath)}`);
65
+ uncheckedFile.keys.forEach((key) => {
66
+ summary.push(` ${DOT}${key}`);
67
+ });
68
+ });
69
+ }
70
+ return summary;
71
+ };
@@ -0,0 +1,6 @@
1
+ import { SnapshotStateType } from 'jest-snapshot';
2
+ import { SnapshotStateOptions } from 'jest-snapshot/build/State';
3
+ import { SnapshotSummary, SnapshotResult } from './types';
4
+ export declare const makeEmptySnapshotSummary: (options: SnapshotStateOptions) => SnapshotSummary;
5
+ export declare const packSnapshotState: (snapshotState: SnapshotStateType) => SnapshotResult;
6
+ export declare const addSnapshotResult: (snapshotSummary: SnapshotSummary, snapshotResult: SnapshotResult, testFilePath: string) => void;
@@ -0,0 +1,65 @@
1
+ /**
2
+ * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
3
+ *
4
+ * This source code is licensed under the MIT license found in the
5
+ * LICENSE file in the root directory of this source tree.
6
+ */
7
+ import Test from '@jest/test-result';
8
+ const { makeEmptyAggregatedTestResult, } = Test;
9
+ export const makeEmptySnapshotSummary = (options) => {
10
+ const summary = makeEmptyAggregatedTestResult().snapshot;
11
+ summary.didUpdate = options.updateSnapshot === 'all';
12
+ return summary;
13
+ };
14
+ export const packSnapshotState = (snapshotState) => {
15
+ const snapshot = {
16
+ added: 0,
17
+ fileDeleted: false,
18
+ matched: 0,
19
+ unchecked: 0,
20
+ uncheckedKeys: [],
21
+ unmatched: 0,
22
+ updated: 0,
23
+ };
24
+ const uncheckedCount = snapshotState.getUncheckedCount();
25
+ const uncheckedKeys = snapshotState.getUncheckedKeys();
26
+ if (uncheckedCount)
27
+ snapshotState.removeUncheckedKeys();
28
+ const status = snapshotState.save();
29
+ snapshot.fileDeleted = status.deleted;
30
+ snapshot.added = snapshotState.added;
31
+ snapshot.matched = snapshotState.matched;
32
+ snapshot.unmatched = snapshotState.unmatched;
33
+ snapshot.updated = snapshotState.updated;
34
+ snapshot.unchecked = !status.deleted ? uncheckedCount : 0;
35
+ // Copy the array to prevent memory leaks
36
+ snapshot.uncheckedKeys = Array.from(uncheckedKeys);
37
+ return snapshot;
38
+ };
39
+ export const addSnapshotResult = (snapshotSummary, snapshotResult, testFilePath) => {
40
+ // Snapshot data
41
+ if (snapshotResult.added)
42
+ snapshotSummary.filesAdded++;
43
+ if (snapshotResult.fileDeleted)
44
+ snapshotSummary.filesRemoved++;
45
+ if (snapshotResult.unmatched)
46
+ snapshotSummary.filesUnmatched++;
47
+ if (snapshotResult.updated)
48
+ snapshotSummary.filesUpdated++;
49
+ snapshotSummary.added += snapshotResult.added;
50
+ snapshotSummary.matched += snapshotResult.matched;
51
+ snapshotSummary.unchecked += snapshotResult.unchecked;
52
+ if (snapshotResult.uncheckedKeys && snapshotResult.uncheckedKeys.length > 0) {
53
+ snapshotSummary.uncheckedKeysByFile.push({
54
+ filePath: testFilePath,
55
+ keys: snapshotResult.uncheckedKeys,
56
+ });
57
+ }
58
+ snapshotSummary.unmatched += snapshotResult.unmatched;
59
+ snapshotSummary.updated += snapshotResult.updated;
60
+ snapshotSummary.total
61
+ += snapshotResult.added
62
+ + snapshotResult.matched
63
+ + snapshotResult.unmatched
64
+ + snapshotResult.updated;
65
+ };
File without changes
@@ -0,0 +1 @@
1
+ "use strict";
@@ -0,0 +1,29 @@
1
+ export interface SnapshotResult {
2
+ added: number;
3
+ fileDeleted: boolean;
4
+ matched: number;
5
+ unchecked: number;
6
+ uncheckedKeys: Array<string>;
7
+ unmatched: number;
8
+ updated: number;
9
+ }
10
+ export interface UncheckedSnapshot {
11
+ filePath: string;
12
+ keys: Array<string>;
13
+ }
14
+ export interface SnapshotSummary {
15
+ added: number;
16
+ didUpdate: boolean;
17
+ failure: boolean;
18
+ filesAdded: number;
19
+ filesRemoved: number;
20
+ filesRemovedList: Array<string>;
21
+ filesUnmatched: number;
22
+ filesUpdated: number;
23
+ matched: number;
24
+ total: number;
25
+ unchecked: number;
26
+ uncheckedKeysByFile: Array<UncheckedSnapshot>;
27
+ unmatched: number;
28
+ updated: number;
29
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,7 @@
1
+ import { Suite } from './types';
2
+ export declare const defaultSuite: Suite;
3
+ export declare const test: (name: string, fn: () => Promise<void> | void) => void;
4
+ export declare function clearContext(): void;
5
+ export declare function suite(suiteName: string, factory?: (test: Suite['test']) => Promise<void> | void): Suite;
6
+ export declare const describe: typeof suite;
7
+ export declare const it: (name: string, fn: () => Promise<void> | void) => void;
package/dist/suite.js ADDED
@@ -0,0 +1,41 @@
1
+ import { context } from './context';
2
+ export const defaultSuite = suite('');
3
+ export const test = (name, fn) => (context.currentSuite || defaultSuite).test(name, fn);
4
+ export function clearContext() {
5
+ context.suites.length = 0;
6
+ defaultSuite.clear();
7
+ }
8
+ export function suite(suiteName, factory) {
9
+ const queue = [];
10
+ const factoryQueue = [];
11
+ const suite = {
12
+ name: suiteName,
13
+ test,
14
+ collect,
15
+ clear,
16
+ };
17
+ function test(name, fn) {
18
+ const task = {
19
+ suite,
20
+ name,
21
+ fn,
22
+ };
23
+ queue.push(task);
24
+ }
25
+ function clear() {
26
+ queue.length = 0;
27
+ factoryQueue.length = 0;
28
+ }
29
+ async function collect() {
30
+ factoryQueue.length = 0;
31
+ if (factory)
32
+ await factory(test);
33
+ return [...factoryQueue, ...queue];
34
+ }
35
+ context.currentSuite = suite;
36
+ context.suites.push(suite);
37
+ return suite;
38
+ }
39
+ // alias
40
+ export const describe = suite;
41
+ export const it = test;
@@ -0,0 +1,33 @@
1
+ export interface UserOptions {
2
+ includes?: string[];
3
+ excludes?: string[];
4
+ }
5
+ export interface Options extends UserOptions {
6
+ rootDir?: string;
7
+ updateSnapshot?: boolean;
8
+ }
9
+ export interface Task {
10
+ name: string;
11
+ suite: Suite;
12
+ fn: () => Promise<void> | void;
13
+ file?: File;
14
+ }
15
+ export interface TaskResult {
16
+ task: Task;
17
+ error?: unknown;
18
+ }
19
+ export interface Suite {
20
+ name: string;
21
+ test: (name: string, fn: () => Promise<void> | void) => void;
22
+ collect: () => Promise<Task[]>;
23
+ clear: () => void;
24
+ }
25
+ export interface File {
26
+ filepath: string;
27
+ suites: Suite[];
28
+ tasks: [Suite, Task[]][];
29
+ }
30
+ export interface GlobalContext {
31
+ suites: Suite[];
32
+ currentSuite: Suite | null;
33
+ }
package/dist/types.js ADDED
@@ -0,0 +1,2 @@
1
+ /* eslint-disable no-use-before-define */
2
+ export {};
@@ -0,0 +1,5 @@
1
+ export declare function createHook<T extends any[]>(): {
2
+ on(fn: (...args: T) => void | Promise<void>): void;
3
+ fire(...args: T): Promise<void>;
4
+ clear(): void;
5
+ };
@@ -0,0 +1,14 @@
1
+ export function createHook() {
2
+ const stacks = [];
3
+ return {
4
+ on(fn) {
5
+ stacks.push(fn);
6
+ },
7
+ async fire(...args) {
8
+ await Promise.all(stacks.map(async (fn) => await fn(...args)));
9
+ },
10
+ clear() {
11
+ stacks.length = 0;
12
+ },
13
+ };
14
+ }
package/package.json CHANGED
@@ -1,6 +1,66 @@
1
1
  {
2
2
  "name": "vitest",
3
- "version": "0.0.0",
4
- "main": "index.js",
5
- "license": "MIT"
3
+ "version": "0.0.4",
4
+ "type": "module",
5
+ "description": "",
6
+ "keywords": [],
7
+ "homepage": "https://github.com/antfu/vitest#readme",
8
+ "bugs": {
9
+ "url": "https://github.com/antfu/vitest/issues"
10
+ },
11
+ "repository": {
12
+ "type": "git",
13
+ "url": "git+https://github.com/antfu/vitest.git"
14
+ },
15
+ "funding": "https://github.com/sponsors/antfu",
16
+ "license": "MIT",
17
+ "author": "Anthony Fu <anthonyfu117@hotmail.com>",
18
+ "exports": {
19
+ ".": {
20
+ "import": "./dist/index.js",
21
+ "types": "./dist/index.d.ts"
22
+ },
23
+ "./*": "./*"
24
+ },
25
+ "main": "./dist/index.js",
26
+ "module": "./dist/index.js",
27
+ "types": "./dist/index.d.ts",
28
+ "files": [
29
+ "dist",
30
+ "bin"
31
+ ],
32
+ "bin": {
33
+ "vitest": "./bin/vitest.mjs"
34
+ },
35
+ "scripts": {
36
+ "build": "tsc",
37
+ "watch": "tsc --watch",
38
+ "lint": "eslint \"{src,test}/**/*.ts\"",
39
+ "prepublishOnly": "nr build",
40
+ "release": "bumpp --commit --push --tag && pnpm publish",
41
+ "test": "node bin/vitest.mjs --dev",
42
+ "test:update": "nr test -u"
43
+ },
44
+ "devDependencies": {
45
+ "@antfu/eslint-config": "^0.11.1",
46
+ "@antfu/ni": "^0.11.0",
47
+ "@types/minimist": "^1.2.2",
48
+ "@types/node": "^16.11.11",
49
+ "bumpp": "^7.1.1",
50
+ "eslint": "^8.3.0",
51
+ "esno": "^0.12.1",
52
+ "typescript": "^4.5.2",
53
+ "vite": "^2.6.14"
54
+ },
55
+ "dependencies": {
56
+ "@types/chai": "^4.2.22",
57
+ "@jest/test-result": "^27.4.2",
58
+ "chai": "^4.3.4",
59
+ "fast-glob": "^3.2.7",
60
+ "jest-snapshot": "^27.4.2",
61
+ "jest-util": "^27.4.2",
62
+ "minimist": "^1.2.5",
63
+ "picocolors": "^1.0.0",
64
+ "vite-node": "^0.1.9"
65
+ }
6
66
  }