vitest 0.0.11 → 0.0.15

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 (52) hide show
  1. package/README.md +56 -3
  2. package/bin/vitest.mjs +1 -39
  3. package/dist/cli.js +3 -2
  4. package/dist/constants.d.ts +1 -0
  5. package/dist/constants.js +20 -0
  6. package/dist/{snapshot/utils/types.js → entry.d.ts} +0 -0
  7. package/dist/entry.js +38 -0
  8. package/dist/global.d.ts +1 -0
  9. package/dist/global.js +8 -0
  10. package/dist/index.d.ts +2 -4
  11. package/dist/index.js +2 -4
  12. package/dist/{chai.js → integrations/chai/index.d.ts} +2 -0
  13. package/dist/integrations/chai/index.js +3 -0
  14. package/dist/integrations/chai/jest-expect.d.ts +21 -0
  15. package/dist/integrations/chai/jest-expect.js +39 -0
  16. package/dist/integrations/chai/setup.d.ts +2 -0
  17. package/dist/integrations/chai/setup.js +12 -0
  18. package/dist/{chai.d.ts → integrations/chai/snapshot/index.d.ts} +6 -1
  19. package/dist/{snapshot → integrations/chai/snapshot}/index.js +1 -1
  20. package/dist/{snapshot → integrations/chai/snapshot}/manager.d.ts +0 -0
  21. package/dist/{snapshot → integrations/chai/snapshot}/manager.js +0 -0
  22. package/dist/{snapshot → integrations/chai/snapshot}/utils/jest-config-helper.d.ts +0 -0
  23. package/dist/{snapshot → integrations/chai/snapshot}/utils/jest-config-helper.js +0 -0
  24. package/dist/{snapshot → integrations/chai/snapshot}/utils/jest-reporters-lite.d.ts +0 -0
  25. package/dist/{snapshot → integrations/chai/snapshot}/utils/jest-reporters-lite.js +0 -0
  26. package/dist/{snapshot → integrations/chai/snapshot}/utils/jest-test-result-helper.d.ts +0 -0
  27. package/dist/{snapshot → integrations/chai/snapshot}/utils/jest-test-result-helper.js +1 -0
  28. package/dist/{snapshot → integrations/chai/snapshot}/utils/types.d.ts +0 -0
  29. package/dist/integrations/chai/snapshot/utils/types.js +1 -0
  30. package/dist/integrations/chai/types.d.ts +3 -0
  31. package/dist/integrations/chai/types.js +1 -0
  32. package/dist/integrations/jsdom.d.ts +5 -0
  33. package/dist/integrations/jsdom.js +20 -0
  34. package/dist/integrations/sinon.d.ts +3 -0
  35. package/dist/integrations/sinon.js +3 -0
  36. package/dist/node.d.ts +11 -0
  37. package/dist/node.js +126 -0
  38. package/dist/reporters/default.js +10 -9
  39. package/dist/run.d.ts +3 -3
  40. package/dist/run.js +51 -38
  41. package/dist/suite.js +1 -1
  42. package/dist/types.d.ts +21 -6
  43. package/dist/types.js +0 -1
  44. package/global.d.ts +21 -0
  45. package/package.json +27 -23
  46. package/dist/defaultIncludes.d.ts +0 -0
  47. package/dist/defaultIncludes.js +0 -1
  48. package/dist/snapshot/index.d.ts +0 -9
  49. package/dist/snapshot/utils/SnapshotResult.d.ts +0 -0
  50. package/dist/snapshot/utils/SnapshotResult.js +0 -1
  51. package/dist/snapshot/utils/tyoes.d.ts +0 -0
  52. package/dist/snapshot/utils/tyoes.js +0 -1
package/README.md CHANGED
@@ -6,10 +6,11 @@ A blazing fast test runner powered by Vite.
6
6
 
7
7
  ## Features
8
8
 
9
- - [Vite](https://vitejs.dev/)'s config, transformers, resolvers, and plugins. Powered by [vite-node](https://github.com/antfu/vite-node)
9
+ - [Vite](https://vitejs.dev/)'s config, transformers, resolvers, and plugins.
10
10
  - [Jest Snapshot](https://jestjs.io/docs/snapshot-testing)
11
11
  - [Chai](https://www.chaijs.com/) for assertions
12
12
  - [Sinon](https://sinonjs.org/) for mocking
13
+ - [JSDOM](https://github.com/jsdom/jsdom) for DOM mocking
13
14
  - Async suite / test, top level await
14
15
  - ESM friendly
15
16
  - Out-of-box TypeScript support
@@ -20,11 +21,12 @@ import { it, describe, expect, assert } from 'vitest'
20
21
 
21
22
  describe('suite name', () => {
22
23
  it('foo', () => {
23
- assert.equal(Math.sqrt(4), 2)
24
+ expect(1 + 1).toEqual(2)
25
+ expect(true).to.be.true
24
26
  })
25
27
 
26
28
  it('bar', () => {
27
- expect(1 + 1).eq(2)
29
+ assert.equal(Math.sqrt(4), 2)
28
30
  })
29
31
 
30
32
  it('snapshot', () => {
@@ -37,6 +39,55 @@ describe('suite name', () => {
37
39
  $ npx vitest
38
40
  ```
39
41
 
42
+ ## Configuration
43
+
44
+ `vitest` will read your root `vite.config.ts` when it present to match with the plugins and setup as your Vite app. If you want to it to have a different configuration for testing, you could either:
45
+
46
+ - Create `vitest.config.ts`, which will have the higher priority
47
+ - Pass `--config` option to CLI, e.g. `vitest --config ./path/to/vitest.config.ts`
48
+ - Use `process.env.VITEST` to conditionally apply differnet configuration in `vite.config.ts`
49
+
50
+ To configure `vitest` itself, add `test` property in your Vite config
51
+
52
+ ```ts
53
+ // vite.config.ts
54
+ import { defineConfig } from 'vite'
55
+
56
+ export default defineConfig({
57
+ test: {
58
+ // ...
59
+ }
60
+ })
61
+ ```
62
+
63
+ ## Global APIs
64
+
65
+ 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.
66
+
67
+ ```ts
68
+ // vite.config.ts
69
+ import { defineConfig } from 'vite'
70
+
71
+ export default defineConfig({
72
+ test: {
73
+ global: true
74
+ }
75
+ })
76
+ ```
77
+
78
+ To get TypeScript working with the global APIs, add `vitest/global` to the `types` filed in your `tsconfig.json`
79
+
80
+ ```json
81
+ // tsconfig.json
82
+ {
83
+ "compilerOptions": {
84
+ "types": [
85
+ "vitest/global"
86
+ ]
87
+ }
88
+ }
89
+ ```
90
+
40
91
  ## Filtering
41
92
 
42
93
  ### Skipping suites and tasks
@@ -103,10 +154,12 @@ describe('suite', () => {
103
154
  - [x] Reporter & Better output
104
155
  - [x] Task filter
105
156
  - [x] Mock
157
+ - [x] Global Mode & Types
106
158
  - [ ] Parallel Executing
107
159
  - [ ] CLI Help
108
160
  - [ ] JSDom
109
161
  - [ ] Watch
162
+ - [ ] Source Map
110
163
  - [ ] Coverage
111
164
 
112
165
  ## Sponsors
package/bin/vitest.mjs CHANGED
@@ -1,42 +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
- const argv = minimist(process.argv.slice(2), {
11
- alias: {
12
- c: 'config',
13
- },
14
- string: ['root', 'config'],
15
- boolean: ['dev'],
16
- })
17
-
18
- const __dirname = dirname(fileURLToPath(import.meta.url))
19
- const root = resolve(argv.root || process.cwd())
20
-
21
- 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 })
22
-
23
- await run({
24
- root,
25
- files: [
26
- resolve(__dirname, argv.dev ? '../src/cli.ts' : '../dist/cli.js'),
27
- ],
28
- config: configPath,
29
- defaultConfig: {
30
- optimizeDeps: {
31
- exclude: [
32
- 'vitest',
33
- ],
34
- },
35
- },
36
- shouldExternalize(id) {
37
- if (id.includes('/node_modules/vitest/'))
38
- return false
39
- else
40
- return id.includes('/node_modules/')
41
- },
42
- })
4
+ import '../dist/entry.js'
package/dist/cli.js CHANGED
@@ -6,9 +6,10 @@ const { log } = console;
6
6
  const argv = minimist(process.argv.slice(2), {
7
7
  alias: {
8
8
  u: 'update',
9
+ w: 'watch',
9
10
  },
10
11
  string: ['root', 'config'],
11
- boolean: ['update', 'dev'],
12
+ boolean: ['update', 'dev', 'global', 'watch', 'jsdom'],
12
13
  unknown(name) {
13
14
  if (name[0] === '-') {
14
15
  console.error(c.red(`Unknown argument: ${name}`));
@@ -22,7 +23,7 @@ const argv = minimist(process.argv.slice(2), {
22
23
  const server = (_a = process === null || process === void 0 ? void 0 : process.__vite_node__) === null || _a === void 0 ? void 0 : _a.server;
23
24
  const viteConfig = (server === null || server === void 0 ? void 0 : server.config) || {};
24
25
  const testOptions = viteConfig.test || {};
25
- await run(Object.assign(Object.assign({}, testOptions), { updateSnapshot: argv.update, rootDir: argv.root || process.cwd() }));
26
+ await run(Object.assign(Object.assign(Object.assign({}, argv), testOptions), { server, updateSnapshot: argv.update, rootDir: argv.root || process.cwd(), nameFilters: argv._ }));
26
27
  function help() {
27
28
  log('Help: finish help');
28
29
  }
@@ -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
+ ];
File without changes
package/dist/entry.js ADDED
@@ -0,0 +1,38 @@
1
+ import { fileURLToPath } from 'url';
2
+ import { resolve, dirname } from 'path';
3
+ import minimist from 'minimist';
4
+ import { findUp } from 'find-up';
5
+ import { run } from './node.js';
6
+ process.env.VITEST = 'true';
7
+ const argv = minimist(process.argv.slice(2), {
8
+ alias: {
9
+ c: 'config',
10
+ },
11
+ string: ['root', 'config'],
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
17
+ ? resolve(root, argv.config)
18
+ : await findUp(['vitest.config.ts', 'vitest.config.js', 'vitest.config.mjs', 'vite.config.ts', 'vite.config.js', 'vite.config.mjs'], { cwd: root });
19
+ await run({
20
+ root,
21
+ files: [
22
+ resolve(__dirname, argv.dev ? '../src/cli.ts' : './cli.js'),
23
+ ],
24
+ config: configPath,
25
+ defaultConfig: {
26
+ optimizeDeps: {
27
+ exclude: [
28
+ 'vitest',
29
+ ],
30
+ },
31
+ },
32
+ shouldExternalize(id) {
33
+ if (id.includes('/node_modules/vitest/'))
34
+ return false;
35
+ else
36
+ return id.includes('/node_modules/');
37
+ },
38
+ });
@@ -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/index.d.ts CHANGED
@@ -1,8 +1,6 @@
1
- import sinon from 'sinon';
2
1
  export * from './types';
3
2
  export * from './suite';
4
3
  export * from './config';
5
- export * from './chai';
4
+ export * from './integrations/chai';
5
+ export * from './integrations/sinon';
6
6
  export { beforeAll, afterAll, beforeEach, afterEach, beforeFile, afterFile, beforeSuite, afterSuite } from './hooks';
7
- export { sinon };
8
- export declare const mock: sinon.SinonMockStatic, spy: sinon.SinonSpyStatic;
package/dist/index.js CHANGED
@@ -1,8 +1,6 @@
1
- import sinon from 'sinon';
2
1
  export * from './types';
3
2
  export * from './suite';
4
3
  export * from './config';
5
- export * from './chai';
4
+ export * from './integrations/chai';
5
+ export * from './integrations/sinon';
6
6
  export { beforeAll, afterAll, beforeEach, afterEach, beforeFile, afterFile, beforeSuite, afterSuite } from './hooks';
7
- export { sinon };
8
- export const { mock, spy } = sinon;
@@ -1 +1,3 @@
1
+ import chai from 'chai';
1
2
  export { assert, should, expect } from 'chai';
3
+ export { chai };
@@ -0,0 +1,3 @@
1
+ import chai from 'chai';
2
+ export { assert, should, expect } from 'chai';
3
+ export { chai };
@@ -0,0 +1,21 @@
1
+ import { ChaiPlugin } from './types';
2
+ export declare function JestChaiExpect(): ChaiPlugin;
3
+ declare global {
4
+ namespace Chai {
5
+ interface Assertion {
6
+ toEqual(expected: any): void;
7
+ toStrictEqual(expected: any): void;
8
+ toBe(expected: any): void;
9
+ toContain(item: any): void;
10
+ toBeTruthy(): void;
11
+ toBeFalsy(): void;
12
+ toBeNaN(): void;
13
+ toBeUndefined(): void;
14
+ toBeNull(): void;
15
+ toBeDefined(): void;
16
+ }
17
+ interface ExpectStatic {
18
+ addSnapshotSerializer: import('pretty-format').Plugin;
19
+ }
20
+ }
21
+ }
@@ -0,0 +1,39 @@
1
+ // Jest Expect Compact
2
+ // TODO: add more https://jestjs.io/docs/expect
3
+ export function JestChaiExpect() {
4
+ return (chai, utils) => {
5
+ const proto = chai.Assertion.prototype;
6
+ utils.addMethod(proto, 'toEqual', function (expected) {
7
+ return this.eql(expected);
8
+ });
9
+ utils.addMethod(proto, 'toStrictEqual', function (expected) {
10
+ return this.equal(expected);
11
+ });
12
+ utils.addMethod(proto, 'toBe', function (expected) {
13
+ return this.be(expected);
14
+ });
15
+ utils.addMethod(proto, 'toContain', function (item) {
16
+ return this.contain(item);
17
+ });
18
+ utils.addMethod(proto, 'toBeTruthy', function () {
19
+ const obj = utils.flag(this, 'object');
20
+ this.assert(Boolean(obj), 'expected #{this} to be truthy', 'expected #{this} to not be truthy', obj);
21
+ });
22
+ utils.addMethod(proto, 'toFalsy', function () {
23
+ const obj = utils.flag(this, 'object');
24
+ this.assert(!obj, 'expected #{this} to be falsy', 'expected #{this} to not be falsy', obj);
25
+ });
26
+ utils.addMethod(proto, 'toBeNaN', function () {
27
+ return this.be.NaN;
28
+ });
29
+ utils.addMethod(proto, 'toBeUndefined', function () {
30
+ return this.be.undefined;
31
+ });
32
+ utils.addMethod(proto, 'toBeNull', function () {
33
+ return this.be.null;
34
+ });
35
+ utils.addMethod(proto, 'toBeDefined', function () {
36
+ return this.not.be.undefined;
37
+ });
38
+ };
39
+ }
@@ -0,0 +1,2 @@
1
+ import { Config } from 'vitest';
2
+ export declare function setupChai(config: Config): Promise<void>;
@@ -0,0 +1,12 @@
1
+ import chai from 'chai';
2
+ import SinonChai from 'sinon-chai';
3
+ import { JestChaiExpect } from './jest-expect';
4
+ import { SnapshotPlugin } from './snapshot';
5
+ export async function setupChai(config) {
6
+ chai.use(SinonChai);
7
+ chai.use(JestChaiExpect());
8
+ chai.use(await SnapshotPlugin({
9
+ rootDir: config.rootDir || process.cwd(),
10
+ update: config.updateSnapshot,
11
+ }));
12
+ }
@@ -1,4 +1,9 @@
1
- export { assert, should, expect } from 'chai';
1
+ import { ChaiPlugin } from '../types';
2
+ export interface SnapshotOptions {
3
+ rootDir: string;
4
+ update?: boolean;
5
+ }
6
+ export declare function SnapshotPlugin(options: SnapshotOptions): Promise<ChaiPlugin>;
2
7
  declare global {
3
8
  namespace Chai {
4
9
  interface Assertion {
@@ -1,5 +1,5 @@
1
1
  import Snap from 'jest-snapshot';
2
- import { afterAll, beforeEach } from '../hooks';
2
+ import { afterAll, beforeEach } from '../../../hooks';
3
3
  import { SnapshotManager } from './manager';
4
4
  const { addSerializer } = Snap;
5
5
  let _manager;
@@ -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) => {
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,3 @@
1
+ import { use as chaiUse } from 'chai';
2
+ export declare type FirstFunctionArgument<T> = T extends (arg: infer A) => unknown ? A : never;
3
+ export declare type ChaiPlugin = FirstFunctionArgument<typeof chaiUse>;
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,5 @@
1
+ import { JSDOM } from 'jsdom';
2
+ export declare function setupJSDOM(global: any): {
3
+ dom: JSDOM;
4
+ restore(): void;
5
+ };
@@ -0,0 +1,20 @@
1
+ import { JSDOM } from 'jsdom';
2
+ export function setupJSDOM(global) {
3
+ const dom = new JSDOM('<!DOCTYPE html>', {
4
+ pretendToBeVisual: true,
5
+ runScripts: 'dangerously',
6
+ // TODO: options
7
+ url: 'http://localhost:3000',
8
+ });
9
+ const keys = Object.getOwnPropertyNames(dom.window)
10
+ .filter(k => !k.startsWith('_'))
11
+ .filter(k => !(k in global));
12
+ for (const key of keys)
13
+ global[key] = dom.window[key];
14
+ return {
15
+ dom,
16
+ restore() {
17
+ keys.forEach(key => delete global[key]);
18
+ },
19
+ };
20
+ }
@@ -0,0 +1,3 @@
1
+ import sinon from 'sinon';
2
+ export { sinon };
3
+ export declare const mock: sinon.SinonMockStatic, spy: sinon.SinonSpyStatic, stub: sinon.SinonStubStatic;
@@ -0,0 +1,3 @@
1
+ import sinon from 'sinon';
2
+ export { sinon };
3
+ export const { mock, spy, stub } = sinon;
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
+ }
@@ -48,13 +48,13 @@ export class DefaultReporter {
48
48
  var _a;
49
49
  // @ts-expect-error
50
50
  (_a = task.__ora) === null || _a === void 0 ? void 0 : _a.stop();
51
- if (task.status === 'pass') {
51
+ if (task.state === 'pass') {
52
52
  this.log(`${c.green(CHECK + task.name)}`);
53
53
  }
54
- else if (task.status === 'skip') {
54
+ else if (task.state === 'skip') {
55
55
  this.log(c.dim(c.yellow(`${DOT + task.name} (skipped)`)));
56
56
  }
57
- else if (task.status === 'todo') {
57
+ else if (task.state === 'todo') {
58
58
  this.log(c.dim(`${DOT + task.name} (todo)`));
59
59
  }
60
60
  else {
@@ -67,10 +67,11 @@ export class DefaultReporter {
67
67
  this.end = performance.now();
68
68
  const failedFiles = files.filter(i => i.error);
69
69
  const tasks = files.reduce((acc, file) => acc.concat(file.suites.flatMap(i => i.tasks)), []);
70
- const passed = tasks.filter(i => i.status === 'pass');
71
- const failed = tasks.filter(i => i.status === 'fail');
72
- const skipped = tasks.filter(i => i.status === 'skip');
73
- const todo = tasks.filter(i => i.status === 'todo');
70
+ const runable = tasks.filter(i => i.state === 'pass' || i.state === 'fail');
71
+ const passed = tasks.filter(i => i.state === 'pass');
72
+ const failed = tasks.filter(i => i.state === 'fail');
73
+ const skipped = tasks.filter(i => i.state === 'skip');
74
+ const todo = tasks.filter(i => i.state === 'todo');
74
75
  this.indent = 0;
75
76
  if (failedFiles.length) {
76
77
  this.error(c.bold(`\nFailed to parse ${failedFiles.length} files:`));
@@ -89,9 +90,9 @@ export class DefaultReporter {
89
90
  this.log();
90
91
  });
91
92
  }
92
- this.log(c.green(`Passed ${passed.length} / ${tasks.length}`));
93
+ this.log(c.green(`Passed ${passed.length} / ${runable.length}`));
93
94
  if (failed.length)
94
- this.log(c.red(`Failed ${failed.length} / ${tasks.length}`));
95
+ this.log(c.red(`Failed ${failed.length} / ${runable.length}`));
95
96
  if (skipped.length)
96
97
  this.log(c.yellow(`Skipped ${skipped.length}`));
97
98
  if (todo.length)
package/dist/run.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { File, Options, Task, RunnerContext } from './types';
1
+ import { File, Config, Task, RunnerContext } from './types';
2
2
  export declare function runTask(task: Task, ctx: RunnerContext): Promise<void>;
3
- export declare function collectFiles(files: string[]): Promise<File[]>;
3
+ export declare function collectFiles(paths: string[]): Promise<File[]>;
4
4
  export declare function runFile(file: File, ctx: RunnerContext): Promise<void>;
5
- export declare function run(options?: Options): Promise<void>;
5
+ export declare function run(config: Config): Promise<void>;
package/dist/run.js CHANGED
@@ -1,39 +1,31 @@
1
- import chai from 'chai';
2
1
  import fg from 'fast-glob';
3
- import SinonChai from 'sinon-chai';
2
+ import { setupChai } from './integrations/chai/setup';
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) {
11
9
  var _a, _b;
12
10
  const { reporter } = ctx;
13
11
  await ((_a = reporter.onTaskBegin) === null || _a === void 0 ? void 0 : _a.call(reporter, task, ctx));
14
- await beforeEachHook.fire(task);
15
- if (task.suite.mode === 'skip' || task.mode === 'skip') {
16
- task.status = 'skip';
17
- }
18
- else if (task.suite.mode === 'todo' || task.mode === 'todo') {
19
- task.status = 'todo';
20
- }
21
- else {
12
+ if (task.mode === 'run') {
13
+ await beforeEachHook.fire(task);
22
14
  try {
23
15
  await task.fn();
24
- task.status = 'pass';
16
+ task.state = 'pass';
25
17
  }
26
18
  catch (e) {
27
- task.status = 'fail';
19
+ task.state = 'fail';
28
20
  task.error = e;
29
21
  }
22
+ await afterEachHook.fire(task);
30
23
  }
31
- await afterEachHook.fire(task);
32
24
  await ((_b = reporter.onTaskEnd) === null || _b === void 0 ? void 0 : _b.call(reporter, task, ctx));
33
25
  }
34
- export async function collectFiles(files) {
35
- const result = [];
36
- for (const filepath of files) {
26
+ export async function collectFiles(paths) {
27
+ const files = [];
28
+ for (const filepath of paths) {
37
29
  const file = {
38
30
  filepath,
39
31
  suites: [],
@@ -54,13 +46,37 @@ export async function collectFiles(files) {
54
46
  file.collected = false;
55
47
  process.exitCode = 1;
56
48
  }
57
- result.push(file);
49
+ files.push(file);
50
+ }
51
+ const allSuites = files.reduce((suites, file) => suites.concat(file.suites), []);
52
+ interpretOnlyMode(allSuites);
53
+ allSuites.forEach((i) => {
54
+ if (i.mode === 'skip')
55
+ i.tasks.forEach(t => t.mode === 'run' && (t.state = 'skip'));
56
+ else
57
+ interpretOnlyMode(i.tasks);
58
+ });
59
+ return files;
60
+ }
61
+ /**
62
+ * If any items been marked as `only`, mark all other items as `skip`.
63
+ */
64
+ function interpretOnlyMode(items) {
65
+ if (items.some(i => i.mode === 'only')) {
66
+ items.forEach((i) => {
67
+ if (i.mode === 'run')
68
+ i.mode = 'skip';
69
+ else if (i.mode === 'only')
70
+ i.mode = 'run';
71
+ });
58
72
  }
59
- return result;
60
73
  }
61
74
  export async function runFile(file, ctx) {
62
75
  var _a, _b, _c, _d;
63
76
  const { reporter } = ctx;
77
+ const runableSuites = file.suites.filter(i => i.mode === 'run');
78
+ if (runableSuites.length === 0)
79
+ return;
64
80
  await ((_a = reporter.onFileBegin) === null || _a === void 0 ? void 0 : _a.call(reporter, file, ctx));
65
81
  await beforeFileHook.fire(file);
66
82
  for (const suite of file.suites) {
@@ -74,42 +90,39 @@ export async function runFile(file, ctx) {
74
90
  await afterFileHook.fire(file);
75
91
  await ((_d = reporter.onFileEnd) === null || _d === void 0 ? void 0 : _d.call(reporter, file, ctx));
76
92
  }
77
- export async function run(options = {}) {
78
- var _a, _b, _c;
79
- const { rootDir = process.cwd() } = options;
93
+ export async function run(config) {
94
+ var _a, _b, _c, _d;
80
95
  // setup chai
81
- chai.use(await SnapshotPlugin({
82
- rootDir,
83
- update: options.updateSnapshot,
84
- }));
85
- chai.use(SinonChai);
96
+ await setupChai(config);
86
97
  // collect files
87
- const paths = await fg(options.includes || defaultIncludes, {
98
+ let paths = await fg(config.includes || defaultIncludes, {
88
99
  absolute: true,
89
- cwd: options.rootDir,
90
- ignore: options.excludes || defaultExcludes,
100
+ cwd: config.rootDir,
101
+ ignore: config.excludes || defaultExcludes,
91
102
  });
103
+ if ((_a = config.nameFilters) === null || _a === void 0 ? void 0 : _a.length)
104
+ paths = paths.filter(i => config.nameFilters.some(f => i.includes(f)));
92
105
  if (!paths.length) {
93
106
  console.error('No test files found');
94
107
  process.exitCode = 1;
95
108
  return;
96
109
  }
97
110
  const reporter = new DefaultReporter();
98
- await ((_a = reporter.onStart) === null || _a === void 0 ? void 0 : _a.call(reporter, options));
111
+ await ((_b = reporter.onStart) === null || _b === void 0 ? void 0 : _b.call(reporter, config));
112
+ if (config.global)
113
+ (await import('./global')).registerApiGlobally();
114
+ if (config.jsdom)
115
+ (await import('./integrations/jsdom')).setupJSDOM(globalThis);
99
116
  const files = await collectFiles(paths);
100
117
  const ctx = {
101
118
  files,
102
- mode: isOnlyMode(files) ? 'only' : 'all',
103
- userOptions: options,
119
+ config,
104
120
  reporter,
105
121
  };
106
- await ((_b = reporter.onCollected) === null || _b === void 0 ? void 0 : _b.call(reporter, ctx));
122
+ await ((_c = reporter.onCollected) === null || _c === void 0 ? void 0 : _c.call(reporter, ctx));
107
123
  await beforeAllHook.fire();
108
124
  for (const file of files)
109
125
  await runFile(file, ctx);
110
126
  await afterAllHook.fire();
111
- await ((_c = reporter.onFinished) === null || _c === void 0 ? void 0 : _c.call(reporter, ctx));
112
- }
113
- function isOnlyMode(files) {
114
- return !!files.find(file => file.suites.find(suite => suite.mode === 'only' || suite.tasks.find(t => t.mode === 'only')));
127
+ await ((_d = reporter.onFinished) === null || _d === void 0 ? void 0 : _d.call(reporter, ctx));
115
128
  }
package/dist/suite.js CHANGED
@@ -22,7 +22,7 @@ function createSuiteCollector(mode, suiteName, factory) {
22
22
  name,
23
23
  mode,
24
24
  suite: {},
25
- status: 'init',
25
+ state: mode !== 'run' ? mode : undefined,
26
26
  fn,
27
27
  });
28
28
  }
package/dist/types.d.ts CHANGED
@@ -1,21 +1,37 @@
1
+ import { ViteDevServer } from 'vite';
1
2
  export declare type Awaitable<T> = Promise<T> | T;
2
3
  export interface UserOptions {
3
4
  includes?: string[];
4
5
  excludes?: string[];
6
+ /**
7
+ * Register apis globally
8
+ *
9
+ * @default false
10
+ */
11
+ global?: boolean;
12
+ /**
13
+ * Use `js-dom` to mock browser APIs
14
+ *
15
+ * @default false
16
+ */
17
+ jsdom?: boolean;
5
18
  }
6
- export interface Options extends UserOptions {
19
+ export interface Config extends UserOptions {
7
20
  rootDir?: string;
8
21
  updateSnapshot?: boolean;
22
+ nameFilters?: string[];
23
+ server: ViteDevServer;
24
+ watch?: boolean;
9
25
  }
10
26
  export declare type RunMode = 'run' | 'skip' | 'only' | 'todo';
11
- export declare type TaskStatus = 'init' | 'pass' | 'fail' | 'skip' | 'todo';
27
+ export declare type TaskState = RunMode | 'pass' | 'fail';
12
28
  export interface Task {
13
29
  name: string;
14
30
  mode: RunMode;
15
31
  suite: Suite;
16
32
  fn: () => Awaitable<void>;
17
33
  file?: File;
18
- status: TaskStatus;
34
+ state?: TaskState;
19
35
  error?: unknown;
20
36
  }
21
37
  export declare type TestFunction = () => Awaitable<void>;
@@ -47,8 +63,7 @@ export interface File {
47
63
  }
48
64
  export interface RunnerContext {
49
65
  files: File[];
50
- mode: 'all' | 'only';
51
- userOptions: Options;
66
+ config: Config;
52
67
  reporter: Reporter;
53
68
  }
54
69
  export interface GlobalContext {
@@ -56,7 +71,7 @@ export interface GlobalContext {
56
71
  currentSuite: SuiteCollector | null;
57
72
  }
58
73
  export interface Reporter {
59
- onStart: (userOptions: Options) => Awaitable<void>;
74
+ onStart: (userOptions: Config) => Awaitable<void>;
60
75
  onCollected: (ctx: RunnerContext) => Awaitable<void>;
61
76
  onFinished: (ctx: RunnerContext) => Awaitable<void>;
62
77
  onSuiteBegin: (suite: Suite, ctx: RunnerContext) => Awaitable<void>;
package/dist/types.js CHANGED
@@ -1,2 +1 @@
1
- /* eslint-disable no-use-before-define */
2
1
  export {};
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.11",
4
- "type": "module",
3
+ "version": "0.0.15",
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,33 +25,23 @@
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
  },
31
+ "files": [
32
+ "dist",
33
+ "bin",
34
+ "*.d.ts"
35
+ ],
35
36
  "scripts": {
36
- "build": "tsc",
37
- "watch": "tsc --watch",
37
+ "prepare": "esmo scripts/generate-types.ts",
38
+ "build": "rimraf dist && tsc -p src/tsconfig.json",
38
39
  "lint": "eslint \"{src,test}/**/*.ts\"",
39
40
  "prepublishOnly": "nr build",
40
41
  "release": "bumpp --commit --push --tag && pnpm publish",
41
42
  "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
- "@types/sinon": "^10.0.6",
50
- "bumpp": "^7.1.1",
51
- "eslint": "^8.3.0",
52
- "esno": "^0.12.1",
53
- "typescript": "^4.5.2",
54
- "vite": "^2.6.14"
43
+ "test:update": "nr test -u",
44
+ "watch": "tsc -p src/tsconfig.json --watch"
55
45
  },
56
46
  "dependencies": {
57
47
  "@jest/test-result": "^27.4.2",
@@ -62,11 +52,25 @@
62
52
  "find-up": "^6.2.0",
63
53
  "jest-snapshot": "^27.4.2",
64
54
  "jest-util": "^27.4.2",
55
+ "jsdom": "^19.0.0",
65
56
  "minimist": "^1.2.5",
66
57
  "ora": "^6.0.1",
67
58
  "picocolors": "^1.0.0",
68
59
  "sinon": "^12.0.1",
69
- "sinon-chai": "^3.7.0",
70
- "vite-node": "^0.1.10"
60
+ "sinon-chai": "^3.7.0"
61
+ },
62
+ "devDependencies": {
63
+ "@antfu/eslint-config": "^0.11.1",
64
+ "@antfu/ni": "^0.11.0",
65
+ "@types/jsdom": "^16.2.13",
66
+ "@types/minimist": "^1.2.2",
67
+ "@types/node": "^16.11.11",
68
+ "@types/sinon": "^10.0.6",
69
+ "bumpp": "^7.1.1",
70
+ "eslint": "^8.3.0",
71
+ "esno": "^0.12.1",
72
+ "rimraf": "^3.0.2",
73
+ "typescript": "^4.5.2",
74
+ "vite": "^2.6.14"
71
75
  }
72
76
  }
File without changes
@@ -1 +0,0 @@
1
- "use strict";
@@ -1,9 +0,0 @@
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): Promise<ChaiPlugin>;
9
- export {};
File without changes
@@ -1 +0,0 @@
1
- "use strict";
File without changes
@@ -1 +0,0 @@
1
- "use strict";