vitest 0.0.12 → 0.0.13

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.
package/README.md CHANGED
@@ -58,6 +58,34 @@ export default defineConfig({
58
58
  })
59
59
  ```
60
60
 
61
+ ## Global APIs
62
+
63
+ By default, `vitest` does not provide global APIs for explicitness. If you prefer to use the APIs globally like Jest, you can pass the `--global` option to CLI or add `global: true` in the config.
64
+
65
+ ```ts
66
+ // vite.config.ts
67
+ import { defineConfig } from 'vite'
68
+
69
+ export default defineConfig({
70
+ test: {
71
+ global: true
72
+ }
73
+ })
74
+ ```
75
+
76
+ To get TypeScript working with the global APIs, add `vitest/global` to the `types` filed in your `tsconfig.json`
77
+
78
+ ```json
79
+ // tsconfig.json
80
+ {
81
+ "compilerOptions": {
82
+ "types": [
83
+ "vitest/global"
84
+ ]
85
+ }
86
+ }
87
+ ```
88
+
61
89
  ## Filtering
62
90
 
63
91
  ### Skipping suites and tasks
@@ -124,7 +152,7 @@ describe('suite', () => {
124
152
  - [x] Reporter & Better output
125
153
  - [x] Task filter
126
154
  - [x] Mock
127
- - [ ] Global Mode & Types
155
+ - [x] Global Mode & Types
128
156
  - [ ] Parallel Executing
129
157
  - [ ] CLI Help
130
158
  - [ ] JSDom
package/bin/vitest.mjs CHANGED
@@ -1,44 +1,4 @@
1
1
  #!/usr/bin/env node
2
2
  'use strict'
3
3
 
4
- import { fileURLToPath } from 'url'
5
- import { resolve, dirname } from 'path'
6
- import { run } from 'vite-node'
7
- import minimist from 'minimist'
8
- import { findUp } from 'find-up'
9
-
10
- process.env.VITEST = 'true'
11
-
12
- const argv = minimist(process.argv.slice(2), {
13
- alias: {
14
- c: 'config',
15
- },
16
- string: ['root', 'config'],
17
- boolean: ['dev'],
18
- })
19
-
20
- const __dirname = dirname(fileURLToPath(import.meta.url))
21
- const root = resolve(argv.root || process.cwd())
22
-
23
- const configPath = argv.config ? resolve(root, argv.config) : await findUp(['vitest.config.ts', 'vitest.config.js', 'vitest.config.mjs', 'vite.config.ts', 'vite.config.js', 'vite.config.mjs'], { cwd: root })
24
-
25
- await run({
26
- root,
27
- files: [
28
- resolve(__dirname, argv.dev ? '../src/cli.ts' : '../dist/cli.js'),
29
- ],
30
- config: configPath,
31
- defaultConfig: {
32
- optimizeDeps: {
33
- exclude: [
34
- 'vitest',
35
- ],
36
- },
37
- },
38
- shouldExternalize(id) {
39
- if (id.includes('/node_modules/vitest/'))
40
- return false
41
- else
42
- return id.includes('/node_modules/')
43
- },
44
- })
4
+ import '../dist/cli.js'
package/dist/chai.d.ts CHANGED
@@ -1,9 +1,18 @@
1
+ import { Config } from 'vitest';
2
+ export declare function setupChai(config: Config): Promise<void>;
1
3
  export { assert, should, expect } from 'chai';
2
4
  declare global {
3
5
  namespace Chai {
4
6
  interface Assertion {
5
7
  toMatchSnapshot(message?: string): Assertion;
6
8
  matchSnapshot(message?: string): Assertion;
9
+ toEqual(expected: any): void;
10
+ toStrictEqual(expected: any): void;
11
+ toContain(item: any): void;
12
+ toBeNaN(): void;
13
+ toBeUndefined(): void;
14
+ toBeNull(): void;
15
+ toBeDefined(): void;
7
16
  }
8
17
  interface ExpectStatic {
9
18
  addSnapshotSerializer: import('pretty-format').Plugin;
package/dist/chai.js CHANGED
@@ -1 +1,37 @@
1
+ import chai from 'chai';
2
+ import SinonChai from 'sinon-chai';
3
+ import { SnapshotPlugin } from './snapshot';
4
+ export async function setupChai(config) {
5
+ chai.use(SinonChai);
6
+ chai.use(await SnapshotPlugin({
7
+ rootDir: config.rootDir || process.cwd(),
8
+ update: config.updateSnapshot,
9
+ }));
10
+ // Jest Compact
11
+ // TODO: add more https://jestjs.io/docs/expect
12
+ chai.use((chai, utils) => {
13
+ const proto = chai.Assertion.prototype;
14
+ utils.addMethod(proto, 'toEqual', function (expected) {
15
+ return this.eql(expected);
16
+ });
17
+ utils.addMethod(proto, 'toStrictEqual', function (expected) {
18
+ return this.equal(expected);
19
+ });
20
+ utils.addMethod(proto, 'toContain', function (item) {
21
+ return this.contain(item);
22
+ });
23
+ utils.addMethod(proto, 'toBeNaN', function () {
24
+ return this.be.NaN;
25
+ });
26
+ utils.addMethod(proto, 'toBeUndefined', function () {
27
+ return this.be.undefined;
28
+ });
29
+ utils.addMethod(proto, 'toBeNull', function () {
30
+ return this.be.null;
31
+ });
32
+ utils.addMethod(proto, 'toBeDefined', function () {
33
+ return this.not.be.undefined;
34
+ });
35
+ });
36
+ }
1
37
  export { assert, should, expect } from 'chai';
@@ -0,0 +1 @@
1
+ export {};
@@ -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', 'global'],
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), { server, global: argv.global, updateSnapshot: argv.update, rootDir: argv.root || process.cwd(), nameFilters: argv._ }));
26
+ function help() {
27
+ log('Help: finish help');
28
+ }
package/dist/cli.js CHANGED
@@ -1,28 +1,36 @@
1
- var _a;
1
+ import { fileURLToPath } from 'url';
2
+ import { resolve, dirname } from 'path';
2
3
  import minimist from 'minimist';
3
- import c from 'picocolors';
4
- import { run } from './run';
5
- const { log } = console;
4
+ import { findUp } from 'find-up';
5
+ import { run } from './node.js';
6
+ process.env.VITEST = 'true';
6
7
  const argv = minimist(process.argv.slice(2), {
7
8
  alias: {
8
- u: 'update',
9
+ c: 'config',
9
10
  },
10
11
  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;
12
+ boolean: ['dev'],
13
+ });
14
+ const __dirname = dirname(fileURLToPath(import.meta.url));
15
+ const root = resolve(argv.root || process.cwd());
16
+ const configPath = argv.config ? resolve(root, argv.config) : await findUp(['vitest.config.ts', 'vitest.config.js', 'vitest.config.mjs', 'vite.config.ts', 'vite.config.js', 'vite.config.mjs'], { cwd: root });
17
+ await run({
18
+ root,
19
+ files: [
20
+ resolve(__dirname, argv.dev ? '../src/cli-entry.ts' : './cli-entry.js'),
21
+ ],
22
+ config: configPath,
23
+ defaultConfig: {
24
+ optimizeDeps: {
25
+ exclude: [
26
+ 'vitest',
27
+ ],
28
+ },
29
+ },
30
+ shouldExternalize(id) {
31
+ if (id.includes('/node_modules/vitest/'))
32
+ return false;
33
+ else
34
+ return id.includes('/node_modules/');
19
35
  },
20
36
  });
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), { server, updateSnapshot: argv.update, rootDir: argv.root || process.cwd(), nameFilters: argv._ }));
26
- function help() {
27
- log('Help: finish help');
28
- }
@@ -1,2 +1,3 @@
1
1
  export declare const defaultIncludes: string[];
2
2
  export declare const defaultExcludes: string[];
3
+ export declare const globalApis: string[];
package/dist/constants.js CHANGED
@@ -1,2 +1,22 @@
1
1
  export const defaultIncludes = ['**/*.{test,spec}.{js,mjs,cjs,ts,mts,cts,jsx,tsx}'];
2
2
  export const defaultExcludes = ['**/node_modules/**', '**/dist/**'];
3
+ export const globalApis = [
4
+ 'suite',
5
+ 'test',
6
+ 'describe',
7
+ 'it',
8
+ 'expect',
9
+ 'assert',
10
+ 'spy',
11
+ 'mock',
12
+ 'stub',
13
+ 'sinon',
14
+ 'beforeAll',
15
+ 'afterAll',
16
+ 'beforeEach',
17
+ 'afterEach',
18
+ 'beforeFile',
19
+ 'afterFile',
20
+ 'beforeSuite',
21
+ 'afterSuite',
22
+ ];
@@ -0,0 +1 @@
1
+ export declare function registerApiGlobally(): void;
package/dist/global.js ADDED
@@ -0,0 +1,8 @@
1
+ import { globalApis } from './constants';
2
+ import * as index from './index';
3
+ export function registerApiGlobally() {
4
+ globalApis.forEach((api) => {
5
+ // @ts-expect-error
6
+ globalThis[api] = index[api];
7
+ });
8
+ }
package/dist/node.d.ts ADDED
@@ -0,0 +1,11 @@
1
+ import { InlineConfig } from 'vite';
2
+ export interface ViteNodeOptions {
3
+ silent?: boolean;
4
+ root: string;
5
+ files: string[];
6
+ _?: string[];
7
+ shouldExternalize?: (file: string) => boolean;
8
+ config?: string;
9
+ defaultConfig?: InlineConfig;
10
+ }
11
+ export declare function run(argv: ViteNodeOptions): Promise<void>;
package/dist/node.js ADDED
@@ -0,0 +1,126 @@
1
+ import { builtinModules, createRequire } from 'module';
2
+ import { pathToFileURL } from 'url';
3
+ import { dirname, resolve, relative } from 'path';
4
+ import vm from 'vm';
5
+ import { createServer, mergeConfig } from 'vite';
6
+ import c from 'picocolors';
7
+ const { red, dim, yellow } = c;
8
+ export async function run(argv) {
9
+ process.exitCode = 0;
10
+ const root = argv.root || process.cwd();
11
+ process.chdir(root);
12
+ const files = argv.files || argv._;
13
+ argv.shouldExternalize = argv.shouldExternalize || (id => id.includes('/node_modules/'));
14
+ const server = await createServer(mergeConfig(argv.defaultConfig || {}, {
15
+ logLevel: 'error',
16
+ clearScreen: false,
17
+ configFile: argv.config,
18
+ root,
19
+ resolve: {},
20
+ }));
21
+ await server.pluginContainer.buildStart({});
22
+ // @ts-expect-error
23
+ process.__vite_node__ = {
24
+ server,
25
+ };
26
+ try {
27
+ await execute(files, server, argv);
28
+ }
29
+ catch (e) {
30
+ process.exitCode = 1;
31
+ throw e;
32
+ }
33
+ finally {
34
+ await server.close();
35
+ }
36
+ }
37
+ function normalizeId(id) {
38
+ // Virtual modules start with `\0`
39
+ if (id && id.startsWith('/@id/__x00__'))
40
+ id = `\0${id.slice('/@id/__x00__'.length)}`;
41
+ if (id && id.startsWith('/@id/'))
42
+ id = id.slice('/@id/'.length);
43
+ return id;
44
+ }
45
+ function toFilePath(id, server) {
46
+ let absolute = id.startsWith('/@fs/')
47
+ ? id.slice(4)
48
+ : id.startsWith(dirname(server.config.root))
49
+ ? id
50
+ : slash(resolve(server.config.root, id.slice(1)));
51
+ if (absolute.startsWith('//'))
52
+ absolute = absolute.slice(1);
53
+ if (!absolute.startsWith('/'))
54
+ absolute = `/${absolute}`;
55
+ return absolute;
56
+ }
57
+ async function execute(files, server, options) {
58
+ const __pendingModules__ = new Map();
59
+ const result = [];
60
+ for (const file of files)
61
+ result.push(await cachedRequest(`/@fs/${slash(resolve(file))}`, []));
62
+ return result;
63
+ async function directRequest(rawId, callstack) {
64
+ if (builtinModules.includes(rawId))
65
+ return import(rawId);
66
+ callstack = [...callstack, rawId];
67
+ const request = async (dep) => {
68
+ if (callstack.includes(dep)) {
69
+ throw new Error(`${red('Circular dependency detected')}\nStack:\n${[...callstack, dep].reverse().map((i) => {
70
+ const path = relative(server.config.root, toFilePath(normalizeId(i), server));
71
+ return dim(' -> ') + (i === dep ? yellow(path) : path);
72
+ }).join('\n')}\n`);
73
+ }
74
+ return cachedRequest(dep, callstack);
75
+ };
76
+ const id = normalizeId(rawId);
77
+ const absolute = toFilePath(id, server);
78
+ if (options.shouldExternalize(absolute))
79
+ return import(absolute);
80
+ const result = await server.transformRequest(id, { ssr: true });
81
+ if (!result)
82
+ throw new Error(`failed to load ${id}`);
83
+ const url = pathToFileURL(absolute);
84
+ const exports = {};
85
+ const context = {
86
+ require: createRequire(url),
87
+ __filename: absolute,
88
+ __dirname: dirname(absolute),
89
+ __vite_ssr_import__: request,
90
+ __vite_ssr_dynamic_import__: request,
91
+ __vite_ssr_exports__: exports,
92
+ __vite_ssr_exportAll__: (obj) => exportAll(exports, obj),
93
+ __vite_ssr_import_meta__: { url },
94
+ };
95
+ const fn = vm.runInThisContext(`async (${Object.keys(context).join(',')}) => { ${result.code} }`, {
96
+ filename: absolute,
97
+ lineOffset: 0,
98
+ });
99
+ await fn(...Object.values(context));
100
+ return exports;
101
+ }
102
+ async function cachedRequest(id, callstack) {
103
+ if (__pendingModules__.has(id))
104
+ return __pendingModules__.get(id);
105
+ __pendingModules__.set(id, directRequest(id, callstack));
106
+ return await __pendingModules__.get(id);
107
+ }
108
+ function exportAll(exports, sourceModule) {
109
+ // eslint-disable-next-line no-restricted-syntax
110
+ for (const key in sourceModule) {
111
+ if (key !== 'default') {
112
+ try {
113
+ Object.defineProperty(exports, key, {
114
+ enumerable: true,
115
+ configurable: true,
116
+ get() { return sourceModule[key]; },
117
+ });
118
+ }
119
+ catch (_err) { }
120
+ }
121
+ }
122
+ }
123
+ }
124
+ function slash(path) {
125
+ return path.replace(/\\/g, '/');
126
+ }
package/dist/run.js CHANGED
@@ -1,10 +1,8 @@
1
- import chai from 'chai';
2
1
  import fg from 'fast-glob';
3
- import SinonChai from 'sinon-chai';
2
+ import { setupChai } from './chai';
4
3
  import { clearContext, defaultSuite } from './suite';
5
4
  import { context } from './context';
6
5
  import { afterEachHook, afterFileHook, afterAllHook, afterSuiteHook, beforeEachHook, beforeFileHook, beforeAllHook, beforeSuiteHook } from './hooks';
7
- import { SnapshotPlugin } from './snapshot';
8
6
  import { DefaultReporter } from './reporters/default';
9
7
  import { defaultIncludes, defaultExcludes } from './constants';
10
8
  export async function runTask(task, ctx) {
@@ -94,13 +92,8 @@ export async function runFile(file, ctx) {
94
92
  }
95
93
  export async function run(config) {
96
94
  var _a, _b, _c, _d;
97
- const { rootDir = process.cwd() } = config;
98
95
  // setup chai
99
- chai.use(await SnapshotPlugin({
100
- rootDir,
101
- update: config.updateSnapshot,
102
- }));
103
- chai.use(SinonChai);
96
+ await setupChai(config);
104
97
  // collect files
105
98
  let paths = await fg(config.includes || defaultIncludes, {
106
99
  absolute: true,
@@ -116,6 +109,8 @@ export async function run(config) {
116
109
  }
117
110
  const reporter = new DefaultReporter();
118
111
  await ((_b = reporter.onStart) === null || _b === void 0 ? void 0 : _b.call(reporter, config));
112
+ if (config.global)
113
+ (await import('./global')).registerApiGlobally();
119
114
  const files = await collectFiles(paths);
120
115
  const ctx = {
121
116
  files,
@@ -4,6 +4,7 @@
4
4
  * This source code is licensed under the MIT license found in the
5
5
  * LICENSE file in the root directory of this source tree.
6
6
  */
7
+ // @ts-ignore
7
8
  import Test from '@jest/test-result';
8
9
  const { makeEmptyAggregatedTestResult, } = Test;
9
10
  export const makeEmptySnapshotSummary = (options) => {
package/dist/types.d.ts CHANGED
@@ -3,6 +3,12 @@ export declare type Awaitable<T> = Promise<T> | T;
3
3
  export interface UserOptions {
4
4
  includes?: string[];
5
5
  excludes?: string[];
6
+ /**
7
+ * Register apis globally
8
+ *
9
+ * @default false
10
+ */
11
+ global?: string;
6
12
  }
7
13
  export interface Config extends UserOptions {
8
14
  rootDir?: string;
package/global.d.ts ADDED
@@ -0,0 +1,21 @@
1
+ declare global {
2
+ const suite: typeof import('vitest')['suite']
3
+ const test: typeof import('vitest')['test']
4
+ const describe: typeof import('vitest')['describe']
5
+ const it: typeof import('vitest')['it']
6
+ const expect: typeof import('vitest')['expect']
7
+ const assert: typeof import('vitest')['assert']
8
+ const spy: typeof import('vitest')['spy']
9
+ const mock: typeof import('vitest')['mock']
10
+ const stub: typeof import('vitest')['stub']
11
+ const sinon: typeof import('vitest')['sinon']
12
+ const beforeAll: typeof import('vitest')['beforeAll']
13
+ const afterAll: typeof import('vitest')['afterAll']
14
+ const beforeEach: typeof import('vitest')['beforeEach']
15
+ const afterEach: typeof import('vitest')['afterEach']
16
+ const beforeFile: typeof import('vitest')['beforeFile']
17
+ const afterFile: typeof import('vitest')['afterFile']
18
+ const beforeSuite: typeof import('vitest')['beforeSuite']
19
+ const afterSuite: typeof import('vitest')['afterSuite']
20
+ }
21
+ export {}
package/package.json CHANGED
@@ -1,7 +1,6 @@
1
1
  {
2
2
  "name": "vitest",
3
- "version": "0.0.12",
4
- "type": "module",
3
+ "version": "0.0.13",
5
4
  "description": "",
6
5
  "keywords": [],
7
6
  "homepage": "https://github.com/antfu/vitest#readme",
@@ -15,6 +14,7 @@
15
14
  "funding": "https://github.com/sponsors/antfu",
16
15
  "license": "MIT",
17
16
  "author": "Anthony Fu <anthonyfu117@hotmail.com>",
17
+ "type": "module",
18
18
  "exports": {
19
19
  ".": {
20
20
  "import": "./dist/index.js",
@@ -25,25 +25,14 @@
25
25
  "main": "./dist/index.js",
26
26
  "module": "./dist/index.js",
27
27
  "types": "./dist/index.d.ts",
28
- "files": [
29
- "dist",
30
- "bin"
31
- ],
32
28
  "bin": {
33
29
  "vitest": "./bin/vitest.mjs"
34
30
  },
35
- "devDependencies": {
36
- "@antfu/eslint-config": "^0.11.1",
37
- "@antfu/ni": "^0.11.0",
38
- "@types/minimist": "^1.2.2",
39
- "@types/node": "^16.11.11",
40
- "@types/sinon": "^10.0.6",
41
- "bumpp": "^7.1.1",
42
- "eslint": "^8.3.0",
43
- "esno": "^0.12.1",
44
- "typescript": "^4.5.2",
45
- "vite": "^2.6.14"
46
- },
31
+ "files": [
32
+ "dist",
33
+ "bin",
34
+ "*.d.ts"
35
+ ],
47
36
  "dependencies": {
48
37
  "@jest/test-result": "^27.4.2",
49
38
  "@types/chai": "^4.2.22",
@@ -57,15 +46,27 @@
57
46
  "ora": "^6.0.1",
58
47
  "picocolors": "^1.0.0",
59
48
  "sinon": "^12.0.1",
60
- "sinon-chai": "^3.7.0",
61
- "vite-node": "^0.1.10"
49
+ "sinon-chai": "^3.7.0"
50
+ },
51
+ "devDependencies": {
52
+ "@antfu/eslint-config": "^0.11.1",
53
+ "@antfu/ni": "^0.11.0",
54
+ "@types/minimist": "^1.2.2",
55
+ "@types/node": "^16.11.11",
56
+ "@types/sinon": "^10.0.6",
57
+ "bumpp": "^7.1.1",
58
+ "eslint": "^8.3.0",
59
+ "esno": "^0.12.1",
60
+ "rimraf": "^3.0.2",
61
+ "typescript": "^4.5.2",
62
+ "vite": "^2.6.14"
62
63
  },
63
64
  "scripts": {
64
- "build": "tsc",
65
- "watch": "tsc --watch",
65
+ "build": "rimraf dist && tsc -p src/tsconfig.json",
66
66
  "lint": "eslint \"{src,test}/**/*.ts\"",
67
67
  "release": "bumpp --commit --push --tag && pnpm publish",
68
68
  "test": "node bin/vitest.mjs --dev",
69
- "test:update": "nr test -u"
69
+ "test:update": "nr test -u",
70
+ "watch": "tsc -p src/tsconfig.json --watch"
70
71
  }
71
72
  }
File without changes
@@ -1 +0,0 @@
1
- "use strict";
File without changes
@@ -1 +0,0 @@
1
- "use strict";
File without changes
@@ -1 +0,0 @@
1
- "use strict";