vitest 0.0.35 → 0.0.36

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/dist/chunk-4OVO6RD6.js +1 -0
  2. package/dist/chunk-CUG6SVUZ.js +1 -0
  3. package/dist/chunk-F27UALKJ.js +1 -0
  4. package/dist/chunk-XPSQDVUG.js +1 -0
  5. package/dist/global-CKRMAXWF.js +1 -0
  6. package/dist/happy-dom-RNJZR3YC.js +1 -0
  7. package/dist/index.d.ts +73 -6
  8. package/dist/index.js +1 -4
  9. package/dist/jsdom-6QAZGE6T.js +1 -0
  10. package/dist/node/cli.d.ts +5 -1
  11. package/dist/node/cli.js +8 -86
  12. package/dist/node/entry.d.ts +1 -1
  13. package/dist/node/entry.js +19 -12
  14. package/dist/{types.d.ts → types-d3253f2d.d.ts} +69 -18
  15. package/package.json +8 -4
  16. package/dist/constants.d.ts +0 -4
  17. package/dist/constants.js +0 -24
  18. package/dist/context.d.ts +0 -2
  19. package/dist/context.js +0 -4
  20. package/dist/integrations/chai/index.d.ts +0 -3
  21. package/dist/integrations/chai/index.js +0 -3
  22. package/dist/integrations/chai/jest-expect.d.ts +0 -2
  23. package/dist/integrations/chai/jest-expect.js +0 -67
  24. package/dist/integrations/chai/setup.d.ts +0 -2
  25. package/dist/integrations/chai/setup.js +0 -11
  26. package/dist/integrations/chai/snapshot/index.d.ts +0 -8
  27. package/dist/integrations/chai/snapshot/index.js +0 -27
  28. package/dist/integrations/chai/snapshot/manager.d.ts +0 -30
  29. package/dist/integrations/chai/snapshot/manager.js +0 -77
  30. package/dist/integrations/chai/snapshot/utils/jest-config-helper.d.ts +0 -3
  31. package/dist/integrations/chai/snapshot/utils/jest-config-helper.js +0 -39
  32. package/dist/integrations/chai/snapshot/utils/jest-reporters-lite.d.ts +0 -2
  33. package/dist/integrations/chai/snapshot/utils/jest-reporters-lite.js +0 -71
  34. package/dist/integrations/chai/snapshot/utils/jest-test-result-helper.d.ts +0 -6
  35. package/dist/integrations/chai/snapshot/utils/jest-test-result-helper.js +0 -66
  36. package/dist/integrations/chai/snapshot/utils/types.d.ts +0 -29
  37. package/dist/integrations/chai/snapshot/utils/types.js +0 -1
  38. package/dist/integrations/chai/types.d.ts +0 -3
  39. package/dist/integrations/chai/types.js +0 -1
  40. package/dist/integrations/dom/happy-dom.d.ts +0 -5
  41. package/dist/integrations/dom/happy-dom.js +0 -18
  42. package/dist/integrations/dom/jsdom.d.ts +0 -5
  43. package/dist/integrations/dom/jsdom.js +0 -21
  44. package/dist/integrations/dom/keys.d.ts +0 -1
  45. package/dist/integrations/dom/keys.js +0 -220
  46. package/dist/integrations/global.d.ts +0 -1
  47. package/dist/integrations/global.js +0 -8
  48. package/dist/integrations/sinon.d.ts +0 -3
  49. package/dist/integrations/sinon.js +0 -5
  50. package/dist/node/node.d.ts +0 -27
  51. package/dist/node/node.js +0 -167
  52. package/dist/reporters/default.d.ts +0 -24
  53. package/dist/reporters/default.js +0 -149
  54. package/dist/reporters/error.d.ts +0 -9
  55. package/dist/reporters/error.js +0 -183
  56. package/dist/run/index.d.ts +0 -8
  57. package/dist/run/index.js +0 -271
  58. package/dist/suite.d.ts +0 -56
  59. package/dist/suite.js +0 -142
  60. package/dist/types.js +0 -1
  61. package/dist/utils/hook.d.ts +0 -5
  62. package/dist/utils/hook.js +0 -14
@@ -0,0 +1 @@
1
+ import{a as k,b as F,f as d}from"./chunk-XPSQDVUG.js";d();var O=["**/*.{test,spec}.{js,mjs,cjs,ts,mts,cts,jsx,tsx}"],R=["**/node_modules/**","**/dist/**"],G=["suite","test","describe","it","chai","expect","assert","sinon","spy","mock","stub","beforeAll","afterAll","beforeEach","afterEach"],C=5e3;d();d();var g={suites:[],currentSuite:null};var y=h("");function s(){return g.currentSuite||y}function x(t,r=()=>{},u){let c=[],i=[],e={name:t,mode:u,hooks:{beforeAll:[],afterAll:[],beforeEach:[],afterEach:[]}},n=j((f,p,a,T)=>{c.push({name:f,mode:a,concurrent:T,suite:{},state:a!=="run"&&a!=="only"?a:void 0,fn:p})}),o={name:t,mode:u,test:n,collect:A,clear:E,on:l};function l(f,...p){e.hooks[f].push(...p)}function E(){c.length=0,i.length=0}async function A(f){i.length=0,r&&await r(n);let p=[...i,...c],a=F(k({},e),{tasks:p,file:f});return p.forEach(T=>{T.suite=a,f&&(T.file=f)}),a}return g.currentSuite=o,g.suites.push(o),o}function b(t){return{timeout:t??C}}function j(t){function r(n,o){t(n,o,"run")}r.concurrent=u,r.skip=c,r.only=i,r.todo=e;function u(n,o,l){t(n,o,"run",b(l))}u.skip=(n,o,l)=>t(n,o,"skip",b(l)),u.only=(n,o,l)=>t(n,o,"only",b(l)),u.todo=e;function c(n,o){t(n,o,"skip")}c.concurrent=u.skip;function i(n,o){t(n,o,"only")}i.concurrent=u.only;function e(n){t(n,()=>{},"todo")}return e.concurrent=e,r}var M=function(){function t(e,n){return s().test(e,n)}function r(e,n,o){return s().test.concurrent(e,n,o)}r.skip=(e,n,o)=>s().test.concurrent.skip(e,n,o),r.only=(e,n,o)=>s().test.concurrent.only(e,n,o),r.todo=e=>s().test.concurrent.todo(e);function u(e,n){return s().test.skip(e,n)}u.concurrent=(e,n,o)=>s().test.skip.concurrent(e,n,o);function c(e,n){return s().test.only(e,n)}c.concurrent=(e,n,o)=>s().test.only.concurrent(e,n,o);function i(e){return s().test.todo(e)}return i.concurrent=e=>s().test.todo.concurrent(e),t.concurrent=r,t.skip=u,t.only=c,t.todo=i,t}();function h(t,r){return x(t,r,"run")}h.skip=(t,r)=>x(t,r,"skip");h.only=(t,r)=>x(t,r,"only");h.todo=t=>x(t,void 0,"todo");var H=h,I=M,P=t=>s().on("beforeAll",t),Q=t=>s().on("afterAll",t),_=t=>s().on("beforeEach",t),z=t=>s().on("afterEach",t);function D(){g.suites.length=0,y.clear(),g.currentSuite=y}export{g as a,O as b,R as c,G as d,y as e,M as f,h as g,H as h,I as i,P as j,Q as k,_ as l,z as m,D as n};
@@ -0,0 +1 @@
1
+ import{e as r,f as a,g as s,h as l,i as c,j as d,k as u,l as p,m as f,n as m}from"./chunk-4OVO6RD6.js";import{d as i,f as e}from"./chunk-XPSQDVUG.js";var T={};i(T,{afterAll:()=>u,afterEach:()=>f,assert:()=>g,beforeAll:()=>d,beforeEach:()=>p,chai:()=>x,clearContext:()=>m,defaultSuite:()=>r,describe:()=>l,expect:()=>C,it:()=>c,mock:()=>b,should:()=>v,sinon:()=>t,spy:()=>k,stub:()=>S,suite:()=>s,test:()=>a});e();e();e();import x from"chai";import{assert as g,should as v,expect as C}from"chai";e();import t from"sinon";var{mock:b,spy:k,stub:S}=t;t.fn=t.spy;export{x as a,g as b,v as c,C as d,t as e,b as f,k as g,S as h,T as i};
@@ -0,0 +1 @@
1
+ import{f as e}from"./chunk-XPSQDVUG.js";e();var t=["DOMException","URL","URLSearchParams","EventTarget","NamedNodeMap","Node","Attr","Element","DocumentFragment","DOMImplementation","Document","XMLDocument","CharacterData","Text","CDATASection","ProcessingInstruction","Comment","DocumentType","NodeList","HTMLCollection","HTMLOptionsCollection","DOMStringMap","DOMTokenList","StyleSheetList","HTMLElement","HTMLHeadElement","HTMLTitleElement","HTMLBaseElement","HTMLLinkElement","HTMLMetaElement","HTMLStyleElement","HTMLBodyElement","HTMLHeadingElement","HTMLParagraphElement","HTMLHRElement","HTMLPreElement","HTMLUListElement","HTMLOListElement","HTMLLIElement","HTMLMenuElement","HTMLDListElement","HTMLDivElement","HTMLAnchorElement","HTMLAreaElement","HTMLBRElement","HTMLButtonElement","HTMLCanvasElement","HTMLDataElement","HTMLDataListElement","HTMLDetailsElement","HTMLDialogElement","HTMLDirectoryElement","HTMLFieldSetElement","HTMLFontElement","HTMLFormElement","HTMLHtmlElement","HTMLImageElement","HTMLInputElement","HTMLLabelElement","HTMLLegendElement","HTMLMapElement","HTMLMarqueeElement","HTMLMediaElement","HTMLMeterElement","HTMLModElement","HTMLOptGroupElement","HTMLOptionElement","HTMLOutputElement","HTMLPictureElement","HTMLProgressElement","HTMLQuoteElement","HTMLScriptElement","HTMLSelectElement","HTMLSlotElement","HTMLSourceElement","HTMLSpanElement","HTMLTableCaptionElement","HTMLTableCellElement","HTMLTableColElement","HTMLTableElement","HTMLTimeElement","HTMLTableRowElement","HTMLTableSectionElement","HTMLTemplateElement","HTMLTextAreaElement","HTMLUnknownElement","HTMLFrameElement","HTMLFrameSetElement","HTMLIFrameElement","HTMLEmbedElement","HTMLObjectElement","HTMLParamElement","HTMLVideoElement","HTMLAudioElement","HTMLTrackElement","SVGElement","SVGGraphicsElement","SVGSVGElement","SVGTitleElement","SVGAnimatedString","SVGNumber","SVGStringList","Event","CloseEvent","CustomEvent","MessageEvent","ErrorEvent","HashChangeEvent","PopStateEvent","StorageEvent","ProgressEvent","PageTransitionEvent","UIEvent","FocusEvent","InputEvent","MouseEvent","KeyboardEvent","TouchEvent","CompositionEvent","WheelEvent","BarProp","External","Location","History","Screen","Performance","Navigator","PluginArray","MimeTypeArray","Plugin","MimeType","FileReader","Blob","File","FileList","ValidityState","DOMParser","XMLSerializer","FormData","XMLHttpRequestEventTarget","XMLHttpRequestUpload","XMLHttpRequest","WebSocket","NodeFilter","NodeIterator","TreeWalker","AbstractRange","Range","StaticRange","Selection","Storage","CustomElementRegistry","ShadowRoot","MutationObserver","MutationRecord","Headers","AbortController","AbortSignal"],n=["addEventListener","alert","atob","blur","btoa","close","confirm","createPopup","dispatchEvent","document","focus","frames","getComputedStyle","history","innerHeight","innerWidth","length","location","moveBy","moveTo","name","navigator","open","outerHeight","outerWidth","pageXOffset","pageYOffset","parent","postMessage","print","prompt","removeEventListener","resizeBy","resizeTo","screen","screenLeft","screenTop","screenX","screenY","scroll","scrollBy","scrollLeft","scrollTo","scrollTop","scrollX","scrollY","self","stop","top","window"],m=t.concat(n);export{m as a};
@@ -0,0 +1 @@
1
+ var f=Object.create;var a=Object.defineProperty,l=Object.defineProperties,_=Object.getOwnPropertyDescriptor,h=Object.getOwnPropertyDescriptors,c=Object.getOwnPropertyNames,e=Object.getOwnPropertySymbols,d=Object.getPrototypeOf,i=Object.prototype.hasOwnProperty,s=Object.prototype.propertyIsEnumerable;var p=(r,t,m)=>t in r?a(r,t,{enumerable:!0,configurable:!0,writable:!0,value:m}):r[t]=m,U=(r,t)=>{for(var m in t||(t={}))i.call(t,m)&&p(r,m,t[m]);if(e)for(var m of e(t))s.call(t,m)&&p(r,m,t[m]);return r},b=(r,t)=>l(r,h(t)),n=r=>a(r,"__esModule",{value:!0});var u=(r,t)=>()=>(r&&(t=r(r=0)),t);var g=(r,t)=>()=>(t||r((t={exports:{}}).exports,t),t.exports),j=(r,t)=>{n(r);for(var m in t)a(r,m,{get:t[m],enumerable:!0})},x=(r,t,m)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of c(t))!i.call(r,o)&&o!=="default"&&a(r,o,{get:()=>t[o],enumerable:!(m=_(t,o))||m.enumerable});return r},k=r=>x(n(a(r!=null?f(d(r)):{},"default",r&&r.__esModule&&"default"in r?{get:()=>r.default,enumerable:!0}:{value:r,enumerable:!0})),r);import{fileURLToPath as L}from"url";import P from"path";var R,y,T=u(()=>{R=L(import.meta.url),y=P.dirname(R)});export{U as a,b,g as c,j as d,k as e,T as f};
@@ -0,0 +1 @@
1
+ import{i as l}from"./chunk-CUG6SVUZ.js";import{d as r}from"./chunk-4OVO6RD6.js";import{f as i}from"./chunk-XPSQDVUG.js";i();function a(){r.forEach(o=>{globalThis[o]=l[o]})}export{a as registerApiGlobally};
@@ -0,0 +1 @@
1
+ import{a as c}from"./chunk-F27UALKJ.js";import{f as n}from"./chunk-XPSQDVUG.js";n();import{Window as p}from"happy-dom";function a(o){let e=new p,r=c.concat(Object.getOwnPropertyNames(e)).filter(t=>!t.startsWith("_")).filter(t=>!(t in o));for(let t of r)o[t]=e[t];return{dom:e,restore(){e.happyDOM.cancelAsync(),r.forEach(t=>delete o[t])}}}export{a as setupHappyDOM};
package/dist/index.d.ts CHANGED
@@ -1,8 +1,73 @@
1
- import { UserOptions } from './types';
2
- export * from './types';
3
- export * from './suite';
4
- export * from './integrations/chai';
5
- export * from './integrations/sinon';
1
+ import * as pretty_format from 'pretty-format';
2
+ import { S as SuiteCollector, T as TestFunction, a as TestFactory, b as Suite, U as UserOptions } from './types-d3253f2d';
3
+ export { C as ConcurrentOptions, F as File, G as GlobalContext, H as HookListener, h as Reporter, R as ResolvedConfig, c as RunMode, g as RunnerContext, b as Suite, S as SuiteCollector, e as Task, d as TaskState, f as TestCollector, a as TestFactory, T as TestFunction, U as UserOptions } from './types-d3253f2d';
4
+ export { assert, default as chai, expect, should } from 'chai';
5
+ import sinon from 'sinon';
6
+ export { default as sinon } from 'sinon';
7
+ import '@antfu/utils';
8
+ import 'jest-snapshot';
9
+ import 'jest-snapshot/build/State';
10
+
11
+ declare const defaultSuite: SuiteCollector;
12
+ declare const test: {
13
+ (name: string, fn: TestFunction): void;
14
+ concurrent: {
15
+ (name: string, fn: TestFunction, timeout?: number | undefined): void;
16
+ skip(name: string, fn: TestFunction, timeout?: number | undefined): void;
17
+ only(name: string, fn: TestFunction, timeout?: number | undefined): void;
18
+ todo(name: string): void;
19
+ };
20
+ skip: {
21
+ (name: string, fn: TestFunction): void;
22
+ concurrent(name: string, fn: TestFunction, timeout?: number | undefined): void;
23
+ };
24
+ only: {
25
+ (name: string, fn: TestFunction): void;
26
+ concurrent(name: string, fn: TestFunction, timeout?: number | undefined): void;
27
+ };
28
+ todo: {
29
+ (name: string): void;
30
+ concurrent(name: string): void;
31
+ };
32
+ };
33
+ declare function suite(suiteName: string, factory?: TestFactory): SuiteCollector;
34
+ declare namespace suite {
35
+ var skip: (suiteName: string, factory?: TestFactory | undefined) => SuiteCollector;
36
+ var only: (suiteName: string, factory?: TestFactory | undefined) => SuiteCollector;
37
+ var todo: (suiteName: string) => SuiteCollector;
38
+ }
39
+ declare const describe: typeof suite;
40
+ declare const it: {
41
+ (name: string, fn: TestFunction): void;
42
+ concurrent: {
43
+ (name: string, fn: TestFunction, timeout?: number | undefined): void;
44
+ skip(name: string, fn: TestFunction, timeout?: number | undefined): void;
45
+ only(name: string, fn: TestFunction, timeout?: number | undefined): void;
46
+ todo(name: string): void;
47
+ };
48
+ skip: {
49
+ (name: string, fn: TestFunction): void;
50
+ concurrent(name: string, fn: TestFunction, timeout?: number | undefined): void;
51
+ };
52
+ only: {
53
+ (name: string, fn: TestFunction): void;
54
+ concurrent(name: string, fn: TestFunction, timeout?: number | undefined): void;
55
+ };
56
+ todo: {
57
+ (name: string): void;
58
+ concurrent(name: string): void;
59
+ };
60
+ };
61
+ declare const beforeAll: (fn: Suite['hooks']['beforeAll'][0]) => void;
62
+ declare const afterAll: (fn: Suite['hooks']['afterAll'][0]) => void;
63
+ declare const beforeEach: (fn: Suite['hooks']['beforeEach'][0]) => void;
64
+ declare const afterEach: (fn: Suite['hooks']['afterEach'][0]) => void;
65
+ declare function clearContext(): void;
66
+
67
+ declare const mock: sinon.SinonMockStatic;
68
+ declare const spy: sinon.SinonSpyStatic;
69
+ declare const stub: sinon.SinonStubStatic;
70
+
6
71
  declare module 'vite' {
7
72
  interface UserConfig {
8
73
  /**
@@ -35,7 +100,9 @@ declare global {
35
100
  toHaveBeenCalledWith(...args: any[]): void;
36
101
  }
37
102
  interface ExpectStatic {
38
- addSnapshotSerializer: import('pretty-format').Plugin;
103
+ addSnapshotSerializer: pretty_format.Plugin;
39
104
  }
40
105
  }
41
106
  }
107
+
108
+ export { afterAll, afterEach, beforeAll, beforeEach, clearContext, defaultSuite, describe, it, mock, spy, stub, suite, test };
package/dist/index.js CHANGED
@@ -1,4 +1 @@
1
- export * from './types';
2
- export * from './suite';
3
- export * from './integrations/chai';
4
- export * from './integrations/sinon';
1
+ import{a as k,b as l,c as m,d as n,e as o,f as p,g as q,h as r}from"./chunk-CUG6SVUZ.js";import{e as a,f as b,g as c,h as d,i as e,j as f,k as g,l as h,m as i,n as j}from"./chunk-4OVO6RD6.js";import"./chunk-XPSQDVUG.js";export{g as afterAll,i as afterEach,l as assert,f as beforeAll,h as beforeEach,k as chai,j as clearContext,a as defaultSuite,d as describe,n as expect,e as it,p as mock,m as should,o as sinon,q as spy,r as stub,c as suite,b as test};
@@ -0,0 +1 @@
1
+ import{a as s}from"./chunk-F27UALKJ.js";import{f as n}from"./chunk-XPSQDVUG.js";n();import{JSDOM as i}from"jsdom";function u(e){let r=new i("<!DOCTYPE html>",{pretendToBeVisual:!0,runScripts:"dangerously",url:"http://localhost:3000"}),o=s.concat(Object.getOwnPropertyNames(r.window)).filter(t=>!t.startsWith("_")).filter(t=>!(t in e));for(let t of o)e[t]=r.window[t];return{dom:r,restore(){o.forEach(t=>delete e[t])}}}export{u as setupJSDOM};
@@ -1,4 +1,8 @@
1
- import type { UserOptions } from '../types';
1
+ import { U as UserOptions } from '../types-d3253f2d';
2
+ import '@antfu/utils';
3
+ import 'jest-snapshot';
4
+ import 'jest-snapshot/build/State';
5
+
2
6
  declare global {
3
7
  namespace NodeJS {
4
8
  interface Process {
package/dist/node/cli.js CHANGED
@@ -1,86 +1,8 @@
1
- /* eslint-disable no-console */
2
- import { fileURLToPath } from 'url';
3
- import { resolve, dirname } from 'path';
4
- import { findUp } from 'find-up';
5
- import sade from 'sade';
6
- import c from 'picocolors';
7
- import { run as startViteNode } from './node.js';
8
- console.log(c.yellow(c.bold('\nVitest is currently in closed beta exclusively for Sponsors')));
9
- console.log(c.magenta(`Become a Sponsor of ${c.underline('https://github.com/sponsors/patak-js')} or ${c.underline('https://github.com/sponsors/antfu')} \nto access the source code and issues tracker 💖\n`));
10
- // TODO: use bundler
11
- const version = '0.0.0';
12
- sade('vitest [filter]', true)
13
- .version(version)
14
- .describe('A blazing fast unit test framework powered by Vite.')
15
- .option('-r, --root', 'root path', process.cwd())
16
- .option('-c, --config', 'path to config file')
17
- .option('-w, --watch', 'watch mode', false)
18
- .option('-u, --update', 'update snapshot', false)
19
- .option('--global', 'inject apis globally', false)
20
- .option('--dev', 'dev mode', false)
21
- .option('--dom', 'mock browser api using jsdom or happy-dom', '')
22
- .action(async (filters, argv) => {
23
- process.env.VITEST = 'true';
24
- const defaultInline = [
25
- 'vue',
26
- '@vue',
27
- 'diff',
28
- ];
29
- const __dirname = dirname(fileURLToPath(import.meta.url));
30
- const root = resolve(argv.root || process.cwd());
31
- const configPath = argv.config
32
- ? resolve(root, argv.config)
33
- : await findUp(['vitest.config.ts', 'vitest.config.js', 'vitest.config.mjs', 'vite.config.ts', 'vite.config.js', 'vite.config.mjs'], { cwd: root });
34
- const options = argv;
35
- options.config = configPath;
36
- options.root = root;
37
- options.filters = filters
38
- ? Array.isArray(filters)
39
- ? filters
40
- : [filters]
41
- : undefined;
42
- process.__vitest__ = {
43
- options,
44
- };
45
- await startViteNode({
46
- root,
47
- files: [
48
- resolve(__dirname, argv.dev ? '../../src/node/entry.ts' : './entry.js'),
49
- ],
50
- config: configPath,
51
- defaultConfig: {
52
- optimizeDeps: {
53
- exclude: [
54
- 'vitest',
55
- ],
56
- },
57
- },
58
- shouldExternalize(id, server) {
59
- var _a, _b, _c, _d;
60
- const inline = ['vitest', ...defaultInline, ...((_b = (_a = server.config.test) === null || _a === void 0 ? void 0 : _a.deps) === null || _b === void 0 ? void 0 : _b.inline) || []];
61
- const external = ((_d = (_c = server.config.test) === null || _c === void 0 ? void 0 : _c.deps) === null || _d === void 0 ? void 0 : _d.external) || [];
62
- for (const ex of inline) {
63
- if (typeof ex === 'string') {
64
- if (id.includes(`/node_modules/${ex}/`))
65
- return false;
66
- }
67
- else {
68
- if (ex.test(id))
69
- return false;
70
- }
71
- }
72
- for (const ex of external) {
73
- if (typeof ex === 'string') {
74
- if (id.includes(`/node_modules/${ex}/`))
75
- return true;
76
- }
77
- else {
78
- if (ex.test(id))
79
- return true;
80
- }
81
- }
82
- return id.includes('/node_modules/');
83
- },
84
- });
85
- })
86
- .parse(process.argv);
1
+ import{f as y}from"../chunk-XPSQDVUG.js";y();import{fileURLToPath as H}from"url";import{resolve as x,dirname as Q}from"path";import{findUp as G}from"find-up";import K from"sade";import v from"picocolors";y();import{builtinModules as z,createRequire as E}from"module";import{fileURLToPath as D,pathToFileURL as W}from"url";import{dirname as j,resolve as R,relative as I}from"path";import M from"vm";import{createServer as N,mergeConfig as U}from"vite";import A from"picocolors";import{slash as w}from"@antfu/utils";var{red:L,dim:k,yellow:F}=A,_=new Map;async function S(e){process.exitCode=0;let t=e.root||process.cwd();process.chdir(t);let n=e.files||e._;e.shouldExternalize=e.shouldExternalize||(i=>i.includes("/node_modules/"));let f=await N(U(e.defaultConfig||{},{logLevel:"error",clearScreen:!1,configFile:e.config,root:t,resolve:{}}));await f.pluginContainer.buildStart({}),process.__vite_node__={server:f,moduleCache:_};try{await B(n,f,e)}catch(i){throw process.exitCode=1,i}finally{process.__vite_node__.watch||await f.close()}}function V(e){return e&&e.startsWith("/@id/__x00__")&&(e=`\0${e.slice("/@id/__x00__".length)}`),e&&e.startsWith("/@id/")&&(e=e.slice("/@id/".length)),e.startsWith("__vite-browser-external:")&&(e=e.slice("__vite-browser-external:".length)),e}function $(e,t){let n=w(e).startsWith("/@fs/")?e.slice(4):e.startsWith(j(t.config.root))?e:e.startsWith("/")?w(R(t.config.root,e.slice(1))):e;return n.startsWith("//")&&(n=n.slice(1)),n}var O={"/@vite/client":{injectQuery:e=>e,createHotContext(){return{accept:()=>{},prune:()=>{}}},updateStyle(){}}};async function J(e,t){if(t.match(/\.(?:[cm]?[jt]sx?|json)$/))return await e.transformRequest(t,{ssr:!0});{let n=await e.transformRequest(t);return n?await e.ssrTransform(n.code,n.map,t):void 0}}function q(e,t){_.has(e)?Object.assign(_.get(e),t):_.set(e,t)}async function B(e,t,n){let f=[];for(let o of e)f.push(await g(`/@fs/${w(R(o))}`,[]));return f;async function i(o,c,r){r=[...r,o];let s=async m=>{if(r.includes(m)){if(!_.get(m))throw new Error(`${L("Circular dependency detected")}
2
+ Stack:
3
+ ${[...r,m].reverse().map(b=>{let C=I(t.config.root,$(V(b),t));return k(" -> ")+(b===m?F(C):C)}).join(`
4
+ `)}
5
+ `);return _.get(m).exports}return g(m,r)};if(o in O)return O[o];let u=await J(t,o);if(!u)throw new Error(`failed to load ${o}`);let p=W(c),a={};q(o,{transformResult:u,exports:a});let h=D(p),l={require:E(p),__filename:h,__dirname:j(h),__vite_ssr_import__:s,__vite_ssr_dynamic_import__:s,__vite_ssr_exports__:a,__vite_ssr_exportAll__:m=>d(a,m),__vite_ssr_import_meta__:{url:p}};return await M.runInThisContext(`async (${Object.keys(l).join(",")}) => { ${u.code} }`,{filename:c,lineOffset:0})(...Object.values(l)),a}async function g(o,c){var p,a;let r=V(o);if(z.includes(r))return import(r);let s=$(r,t);if(n.shouldExternalize(s,t))return import(s);if((p=_.get(s))==null?void 0:p.promise)return(a=_.get(s))==null?void 0:a.promise;let u=i(r,s,c);return q(s,{promise:u}),await u}function d(o,c){for(let r in c)if(r!=="default")try{Object.defineProperty(o,r,{enumerable:!0,configurable:!0,get(){return c[r]}})}catch{}}}console.log(v.yellow(v.bold(`
6
+ Vitest is currently in closed beta exclusively for Sponsors`)));console.log(v.magenta(`Become a Sponsor of ${v.underline("https://github.com/sponsors/patak-js")} or ${v.underline("https://github.com/sponsors/antfu")}
7
+ to access the source code and issues tracker \u{1F496}
8
+ `));var X="0.0.0";K("vitest [filter]",!0).version(X).describe("A blazing fast unit test framework powered by Vite.").option("-r, --root","root path",process.cwd()).option("-c, --config","path to config file").option("-w, --watch","watch mode",!1).option("-u, --update","update snapshot",!1).option("--global","inject apis globally",!1).option("--dev","dev mode",!1).option("--dom","mock browser api using jsdom or happy-dom","").action(async(e,t)=>{process.env.VITEST="true";let n=["vue","@vue","diff"],f=Q(H(import.meta.url)),i=x(t.root||process.cwd()),g=t.config?x(i,t.config):await G(["vitest.config.ts","vitest.config.js","vitest.config.mjs","vite.config.ts","vite.config.js","vite.config.mjs"],{cwd:i}),d=t;d.config=g,d.root=i,d.filters=e?Array.isArray(e)?e:[e]:void 0,process.__vitest__={options:d},await S({root:i,files:[x(f,t.dev?"../../src/node/entry.ts":"./entry.js")],config:g,defaultConfig:{optimizeDeps:{exclude:["vitest"]}},shouldExternalize(o,c){var u,p,a,h;let r=["vitest",...n,...((p=(u=c.config.test)==null?void 0:u.deps)==null?void 0:p.inline)||[]],s=((h=(a=c.config.test)==null?void 0:a.deps)==null?void 0:h.external)||[];for(let l of r)if(typeof l=="string"){if(o.includes(`/node_modules/${l}/`))return!1}else if(l.test(o))return!1;for(let l of s)if(typeof l=="string"){if(o.includes(`/node_modules/${l}/`))return!0}else if(l.test(o))return!0;return o.includes("/node_modules/")}})}).parse(process.argv);
@@ -1 +1 @@
1
- export {};
1
+
@@ -1,12 +1,19 @@
1
- import { run } from '../run';
2
- if (!process.__vite_node__ || !process.__vitest__)
3
- throw new Error('Vitest can only run in vite-node environment, please use the CLI to start the process');
4
- const inlineOptions = process.__vite_node__.server.config.test || {};
5
- const cliOptions = process.__vitest__.options || {};
6
- const options = Object.assign(Object.assign({}, cliOptions), inlineOptions);
7
- await run(options);
8
- const timer = setTimeout(() => {
9
- // TODO: warn user and maybe error out
10
- process.exit();
11
- }, 500);
12
- timer.unref();
1
+ import{a as O,b as U,c as H,e as W,n as I}from"../chunk-4OVO6RD6.js";import{a as x,c as pe,e as me,f as h}from"../chunk-XPSQDVUG.js";var J=pe((st,G)=>{h();"use strict";G.exports=t=>{let e=/^\\\\\?\\/.test(t),n=/[^\u0000-\u0080]+/.test(t);return e||n?t:t.replace(/\\/g,"/")}});h();h();import ze from"fast-glob";import{slash as Ge}from"@antfu/utils";h();import T from"chai";import xe from"sinon-chai";import Oe from"chai-subset";h();function K(){return(t,e)=>{let n=t.Assertion.prototype;e.addMethod(n,"toEqual",function(o){return this.eql(o)}),e.addMethod(n,"toStrictEqual",function(o){return this.equal(o)}),e.addMethod(n,"toBe",function(o){return this.equal(o)}),e.addMethod(n,"toMatchObject",function(o){return this.containSubset(o)}),e.addMethod(n,"toMatch",function(o){return typeof o=="string"?this.include(o):this.match(o)}),e.addMethod(n,"toContain",function(o){return this.contain(o)}),e.addMethod(n,"toBeTruthy",function(){let o=e.flag(this,"object");this.assert(Boolean(o),"expected #{this} to be truthy","expected #{this} to not be truthy",o)}),e.addMethod(n,"toBeFalsy",function(){let o=e.flag(this,"object");this.assert(!o,"expected #{this} to be falsy","expected #{this} to not be falsy",o)}),e.addMethod(n,"toBeNaN",function(){return this.be.NaN}),e.addMethod(n,"toBeUndefined",function(){return this.be.undefined}),e.addMethod(n,"toBeNull",function(){return this.be.null}),e.addMethod(n,"toBeDefined",function(){return this.not.be.undefined}),e.addMethod(n,"toBeInstanceOf",function(o){return this.instanceOf(o)}),e.addMethod(n,"toHaveBeenCalledTimes",function(o){return this.callCount(o)}),e.addMethod(n,"toHaveBeenCalledOnce",function(){return this.callCount(1)}),e.addMethod(n,"toHaveBeenCalled",function(){return this.called}),e.addMethod(n,"toHaveBeenCalled",function(){return this.called}),e.addMethod(n,"toHaveBeenCalledWith",function(...o){return this.calledWith(...o)})}}h();import ee from"jest-snapshot";h();import Ce from"chai";import be from"jest-snapshot";h();import ge from"@jest/test-result";var{makeEmptyAggregatedTestResult:Se}=ge,A=t=>{let e=Se().snapshot;return e.didUpdate=t.updateSnapshot==="all",e},q=t=>{let e={added:0,fileDeleted:!1,matched:0,unchecked:0,uncheckedKeys:[],unmatched:0,updated:0},n=t.getUncheckedCount(),o=t.getUncheckedKeys();n&&t.removeUncheckedKeys();let r=t.save();return e.fileDeleted=r.deleted,e.added=t.added,e.matched=t.matched,e.unmatched=t.unmatched,e.updated=t.updated,e.unchecked=r.deleted?0:n,e.uncheckedKeys=Array.from(o),e},z=(t,e,n)=>{e.added&&t.filesAdded++,e.fileDeleted&&t.filesRemoved++,e.unmatched&&t.filesUnmatched++,e.updated&&t.filesUpdated++,t.added+=e.added,t.matched+=e.matched,t.unchecked+=e.unchecked,e.uncheckedKeys&&e.uncheckedKeys.length>0&&t.uncheckedKeysByFile.push({filePath:n,keys:e.uncheckedKeys}),t.unmatched+=e.unmatched,t.updated+=e.updated,t.total+=e.added+e.matched+e.unmatched+e.updated};h();var V=me(J());import C,{isAbsolute as ye}from"path";import{pluralize as p}from"jest-util";import m from"picocolors";var P=(t,e)=>{ye(e)&&(e=C.relative(t,e));let n=C.dirname(e),o=C.basename(e);return(0,V.default)(m.dim(n+C.sep)+m.bold(o))},$=" \u203A ",Y=" \u21B3 ",_=" \u2022 ",ke=t=>m.bold(m.red(t)),Q=t=>m.bold(m.yellow(t)),we=t=>m.bold(m.green(t)),E=m.dim,X=t=>m.bold(m.green(t)),$e=m.bold,ve=t=>m.bold(m.green(t)),F="re-run mocha with `--update` to update them",Z=(t,e)=>{let n=[];if(n.push($e("Snapshot Summary")),e.added&&n.push(`${we(`${$+p("snapshot",e.added)} written `)}from ${p("test suite",e.filesAdded)}.`),e.unmatched&&n.push(`${ke(`${$}${p("snapshot",e.unmatched)} failed`)} from ${p("test suite",e.filesUnmatched)}. ${E(`Inspect your code changes or ${F} to update them.`)}`),e.updated&&n.push(`${ve(`${$+p("snapshot",e.updated)} updated `)}from ${p("test suite",e.filesUpdated)}.`),e.filesRemoved&&(e.didUpdate?n.push(`${X(`${$}${p("snapshot file",e.filesRemoved)} removed `)}from ${p("test suite",e.filesRemoved)}.`):n.push(`${Q(`${$}${p("snapshot file",e.filesRemoved)} obsolete `)}from ${p("test suite",e.filesRemoved)}. ${E(`To remove ${e.filesRemoved===1?"it":"them all"}, ${F}.`)}`)),e.filesRemovedList&&e.filesRemovedList.length){let[o,...r]=e.filesRemovedList;n.push(` ${Y} ${_}${P(t,o)}`),r.forEach(s=>{n.push(` ${_}${P(t,s)}`)})}return e.unchecked&&(e.didUpdate?n.push(`${X(`${$}${p("snapshot",e.unchecked)} removed `)}from ${p("test suite",e.uncheckedKeysByFile.length)}.`):n.push(`${Q(`${$}${p("snapshot",e.unchecked)} obsolete `)}from ${p("test suite",e.uncheckedKeysByFile.length)}. ${E(`To remove ${e.unchecked===1?"it":"them all"}, ${F}.`)}`),e.uncheckedKeysByFile.forEach(o=>{n.push(` ${Y}${P(t,o.filePath)}`),o.keys.forEach(r=>{n.push(` ${_}${r}`)})})),n};var{expect:Te}=Ce,{SnapshotState:Me}=be,j=class{snapshotState=null;snapshotSummary;snapshotOptions;context=null;testFile="";snapshotResolver;rootDir;constructor({rootDir:e,update:n,snapshotResolver:o=null}){this.rootDir=e,this.snapshotResolver=o;let r=process.env,s=!!r.CI,i=n||r.UPDATE_SNAPSHOT;this.snapshotOptions={updateSnapshot:s&&!i?"none":i?"all":"new"},this.snapshotSummary=A(this.snapshotOptions)}onFileChanged(){!this.context||(this.snapshotState!==null&&this.saveSnap(),this.testFile=this.context.file,this.snapshotState=new Me(this.snapshotResolver.resolveSnapshotPath(this.testFile),this.snapshotOptions))}setTask(e){var n;this.setContext({file:((n=e.file)==null?void 0:n.filepath)||e.name,title:e.name,fullTitle:[e.suite.name,e.name].filter(Boolean).join(" > ")})}setContext(e){!e.title||!e.file||(this.context=e,this.testFile!==e.file&&this.onFileChanged())}assert(e,n){if(!this.snapshotState||!this.context)return;let{actual:o,expected:r,key:s,pass:i}=this.snapshotState.match({testName:this.context.fullTitle||this.context.title||this.context.file,received:e,isInline:!1});i||Te(o.trim()).equals(r?r.trim():"",n||`Snapshot name: \`${s}\``)}clear(){this.snapshotSummary=A(this.snapshotOptions)}saveSnap(){if(!this.testFile||!this.snapshotState)return;let e=q(this.snapshotState);z(this.snapshotSummary,e,this.testFile),this.testFile="",this.snapshotState=null}report(){let e=Z(this.rootDir,this.snapshotSummary);if(e.length>1)return e}};var{addSerializer:Re}=ee,b;function B(){return b}async function te(t){let{root:e}=t;return b=new j({rootDir:e,update:t.update}),b.snapshotResolver=await ee.buildSnapshotResolver({transform:[],rootDir:e}),function(n,o){for(let r of["matchSnapshot","toMatchSnapshot"])o.addMethod(n.Assertion.prototype,r,function(s){let i=o.flag(this,"object");b.assert(i,s)});n.expect.addSnapshotSerializer=Re}}async function ne(t){T.use(xe),T.use(K()),T.use(Oe),T.use(await te(t))}h();import{performance as ie}from"perf_hooks";import{relative as Ke}from"path";import c from"picocolors";import D from"listr";h();import{promises as Ae,existsSync as Pe}from"fs";import S from"picocolors";import{createPatch as Ie}from"diff";import{notNullish as _e}from"@antfu/utils";import{SourceMapConsumer as Ee}from"source-map";async function M(t){var i;if(!(t instanceof Error)){console.error(t);return}let{moduleCache:e}=process.__vite_node__,n=t,o=!1,s=Ne(n.stack||"").find(a=>e.has(a.file));if(s){let a=(i=e.get(s.file))==null?void 0:i.transformResult,d=await Fe(a==null?void 0:a.map,s);if(d&&Pe(s.file)){let f=await Ae.readFile(s.file,"utf-8");console.error(`${S.red(`${S.bold(n.name)}: ${n.message}`)}`),console.log(S.gray(`${s.file}:${d.line}:${d.column}`)),console.log(S.yellow(Be(f,d))),o=!0}}o||console.error(n),n.showDiff&&console.error(S.gray(Ue(se(n.actual),se(n.expected))))}function Fe(t,{line:e,column:n}){return new Promise(o=>{if(!t)return o(null);Ee.with(t,null,r=>{let s=r.originalPositionFor({line:e,column:n});s.line!=null&&s.column!=null?o(s):o(null)})})}var oe=/\r?\n/;function je(t,e){if(typeof e=="number")return e;let n=t.split(oe),{line:o,column:r}=e,s=0;for(let i=0;i<o-1;i++)s+=n[i].length+1;return s+r}function Be(t,e=0,n,o=2){e=je(t,e),n=n||e;let r=t.split(oe),s=0,i=[];for(let a=0;a<r.length;a++)if(s+=r[a].length+1,s>=e){for(let d=a-o;d<=a+o||n>s;d++){if(d<0||d>=r.length)continue;let f=d+1;i.push(`${S.gray(`${f}${" ".repeat(Math.max(3-String(f).length,0))}|`)} ${r[d]}`);let u=r[d].length;if(d===a){let g=e-(s-u)+1,w=Math.max(1,n>s?u-g:n-e);i.push(`${S.gray(" |")} ${" ".repeat(g)}${"^".repeat(w)}`)}else if(d>a){if(n>s){let g=Math.max(Math.min(n-s,u),1);i.push(`${S.gray(" |")} ${"^".repeat(g)}`)}s+=u+1}}break}return i.join(`
2
+ `)}function se(t){return String(t)}var De=/at (.*) \((.+):(\d+):(\d+)\)$/,Le=/at ()(.+):(\d+):(\d+)$/;function Ne(t){return t.split(`
3
+ `).map(o=>{let r=o.trim(),s=r.match(De)||r.match(Le);if(!s)return null;let i=s[2];return i.startsWith("file://")&&(i=i.slice(7)),{method:s[1],file:s[2],line:parseInt(s[3]),column:parseInt(s[4])}}).filter(_e)}function Ue(t,e){let n=2048;return t.length>n&&(t=`${t.substring(0,n)} ... Lines skipped`),e.length>n&&(e=`${e.substring(0,n)} ... Lines skipped`),He(t,e)}function He(t,e){let n=" ";function o(i){return i[0]==="+"?n+S.green(`${i[0]} ${i.slice(1)}`):i[0]==="-"?n+S.red(`${i[0]} ${i.slice(1)}`):i.match(/@@/)?"--":i.match(/\\ No newline/)?null:n+i}let s=Ie("string",t,e).split(`
4
+ `).splice(5);return`
5
+ ${n}${S.red("- actual")}
6
+ ${n}${S.green("+ expected")}
7
+
8
+ ${s.map(o).filter(We).join(`
9
+ `)}`}function We(t){return typeof t!="undefined"&&t!==null}var qe="\u2716 ",L=class{start=0;end=0;listr=null;listrPromise=null;taskMap=new Map;cwd=process.cwd();relative(e){return Ke(this.cwd,e)}onStart(e){this.cwd=e.root,console.log(c.green(`Running tests under ${c.gray(this.cwd)}
10
+ `))}onCollected(e){this.start=ie.now(),this.taskMap=new Map,e.reduce((s,i)=>s.concat(i.suites.flatMap(a=>a.tasks)),[]).forEach(s=>{let i={};i.promise=new Promise((a,d)=>{i.resolve=a,i.reject=d}),this.taskMap.set(s,i)});let o=s=>s.map(i=>({title:i.name,skip:()=>i.mode==="skip",task:async()=>{var a;return await((a=this.taskMap.get(i))==null?void 0:a.promise)}})),r={exitOnError:!1};this.listr=new D(e.map(s=>({title:this.relative(s.filepath),task:()=>{if(s.error)throw s.error;let i=s.suites.filter(a=>a.tasks.length);if(!i.length)throw new Error("No tasks found");return new D(i.flatMap(a=>a.name?[{title:a.name,skip:()=>a.mode!=="run",task:()=>new D(o(a.tasks),r)}]:o(a.tasks)),r)}})),r),this.listrPromise=this.listr.run().catch(()=>{})}onTaskEnd(e){var n,o;e.state==="fail"?(n=this.taskMap.get(e))==null||n.reject(e.error):(o=this.taskMap.get(e))==null||o.resolve()}async onFinished(e,n=e.files){var v;await this.listrPromise,this.end=ie.now(),console.log();let o=e.snapshotManager.report();o&&console.log(o.join(`
11
+ `));let r=n.flatMap(l=>l.suites),s=r.flatMap(l=>l.tasks),i=n.filter(l=>l.error),a=r.filter(l=>l.error),d=s.filter(l=>l.state==="pass"||l.state==="fail"),f=s.filter(l=>l.state==="pass"),u=s.filter(l=>l.state==="fail"),g=s.filter(l=>l.state==="skip"),w=s.filter(l=>l.state==="todo");if(i.length){console.error(c.red(c.bold(`
12
+ Failed to parse ${i.length} files:`)));for(let l of i)console.error(c.red(`- ${l.filepath}`));console.log();for(let l of i)await M(l.error),console.log()}if(a.length){console.error(c.bold(c.red(`
13
+ Failed to run ${a.length} suites:`)));for(let l of a)console.error(c.red(`
14
+ - ${(v=l.file)==null?void 0:v.filepath} > ${l.name}`)),await M(l.error),console.log()}if(u.length){console.error(c.bold(c.red(`
15
+ Failed Tests (${u.length})`)));for(let l of u)console.error(`${c.red(`
16
+ ${qe+c.inverse(" FAIL ")}`)} ${[l.suite.name,l.name].filter(Boolean).join(" > ")}`),await M(l.error),console.log()}console.log(c.bold(c.green(`Passed ${f.length} / ${d.length}`))),u.length&&console.log(c.bold(c.red(`Failed ${u.length} / ${d.length}`))),g.length&&console.log(c.yellow(`Skipped ${g.length}`)),w.length&&console.log(c.dim(`Todo ${w.length}`)),console.log(`Time ${(this.end-this.start).toFixed(2)}ms`)}async onWatcherStart(e){await this.listrPromise;let n=e.tasks.filter(o=>o.state==="fail");n.length?console.log(`
17
+ ${c.bold(c.inverse(c.red(" FAIL ")))}${c.red(` ${n.length} tests failed. Watching for file changes...`)}`):console.log(`
18
+ ${c.bold(c.inverse(c.green(" PASS ")))}${c.green(" Watching for file changes...")}`)}async onWatcherRerun(e,n){await this.listrPromise,console.clear(),console.log(c.blue("Re-running tests...")+c.dim(` [ ${this.relative(n)} ]
19
+ `))}onSnapshotUpdate(){}};async function R(t,e,n){await Promise.all(t.hooks[e].map(o=>o(...n)))}async function re(t,e){var o,r,s;let{reporter:n}=e;if((o=B())==null||o.setTask(t),await((r=n.onTaskBegin)==null?void 0:r.call(n,t,e)),t.mode==="run"){try{await R(t.suite,"beforeEach",[t,t.suite]),await t.fn(),t.state="pass"}catch(i){t.state="fail",t.error=i,process.exitCode=1}try{await R(t.suite,"afterEach",[t,t.suite])}catch(i){t.state="fail",t.error=i,process.exitCode=1}}await((s=n.onTaskEnd)==null?void 0:s.call(n,t,e))}async function ae(t){let e={};for(let r of t){let s={filepath:r,suites:[],collected:!1};I();try{await import(r);let i=[W,...O.suites];for(let a of i)O.currentSuite=a,s.suites.push(await a.collect(s));s.collected=!0}catch(i){s.error=i,s.collected=!1,process.exitCode=1}e[r]=s}let o=Object.values(e).reduce((r,s)=>r.concat(s.suites),[]);return le(o),o.forEach(r=>{r.mode==="skip"?r.tasks.forEach(s=>s.mode==="run"&&(s.mode="skip")):le(r.tasks),r.tasks.forEach(s=>s.mode==="skip"&&(s.state="skip"))}),e}function le(t){t.some(e=>e.mode==="only")&&t.forEach(e=>{e.mode==="run"?e.mode="skip":e.mode==="only"&&(e.mode="run")})}async function ce(t,e){var o,r;let{reporter:n}=e;if(await((o=n.onSuiteBegin)==null?void 0:o.call(n,t,e)),t.mode==="skip")t.status="skip";else if(t.mode==="todo")t.status="todo";else try{await R(t,"beforeAll",[t]);for(let s of Je(t.tasks))if(s[0].concurrent)await Promise.all(s.map(i=>re(i,e)));else for(let i of s)await re(i,e);await R(t,"afterAll",[t])}catch(s){t.error=s,t.status="fail",process.exitCode=1}await((r=n.onSuiteEnd)==null?void 0:r.call(n,t,e))}function Je(t){let e=[],n=[];for(let o of t)e.length===0||!!o.concurrent==!!e[0].concurrent?e.push(o):(n.push(e),e=[o]);return e.length>0&&n.push(e),n}async function Ve(t,e){var r,s;let{reporter:n}=e;if(t.suites.filter(i=>i.mode==="run").length!==0){if(await((r=n.onFileBegin)==null?void 0:r.call(n,t,e)),e.config.parallel)await Promise.all(t.suites.map(i=>ce(i,e)));else for(let i of t.suites)await ce(i,e);await((s=n.onFileEnd)==null?void 0:s.call(n,t,e))}}async function de(t,e){var o;let{reporter:n}=e;await((o=n.onCollected)==null?void 0:o.call(n,Object.values(t),e));for(let r of Object.values(t))await Ve(r,e)}async function he(t){var i,a,d;t.reporter=t.reporter||new L;let{reporter:e}=t;t.watch&&(process.__vite_node__.watch=!0),await ne(t);let n=await ze(t.includes||U,{absolute:!0,cwd:t.root,ignore:t.excludes||H});if(((i=t.filters)==null?void 0:i.length)&&(n=n.filter(f=>t.filters.some(u=>f.includes(u)))),!n.length){console.error("No test files found"),process.exitCode=1;return}t.global&&(await import("../global-CKRMAXWF.js")).registerApiGlobally(),t.dom==="happy-dom"?(await import("../happy-dom-RNJZR3YC.js")).setupHappyDOM(globalThis):t.dom&&(await import("../jsdom-6QAZGE6T.js")).setupJSDOM(globalThis),await((a=e.onStart)==null?void 0:a.call(e,t));let o=await ae(n),r=B(),s={filesMap:o,get files(){return Object.values(this.filesMap)},get suites(){return Object.values(this.filesMap).reduce((f,u)=>f.concat(u.suites),[])},get tasks(){return this.suites.reduce((f,u)=>f.concat(u.tasks),[])},config:t,reporter:e,snapshotManager:r};await de(o,s),r.saveSnap(),await((d=e.onFinished)==null?void 0:d.call(e,s)),t.watch&&await Ye(s)}async function Ye(t){var f;let{reporter:e,snapshotManager:n,filesMap:o}=t;await((f=e.onWatcherStart)==null?void 0:f.call(e,t));let r,s=new Set,i=new Set,{server:a,moduleCache:d}=process.__vite_node__;a.watcher.on("change",async u=>{u=Ge(u),ue(u,t,s,i),i.forEach(g=>d.delete(g)),i.clear(),s.size!==0&&(clearTimeout(r),r=setTimeout(async()=>{var v,l,N;if(s.size===0)return;n.clear();let g=Array.from(s);s.clear(),await((v=e.onWatcherRerun)==null?void 0:v.call(e,g,u,t)),g.forEach(fe=>d.delete(fe));let w=await ae(g);Object.assign(o,w),await de(w,t),n.saveSnap(),await((l=e.onFinished)==null?void 0:l.call(e,t,Object.values(w))),await((N=e.onWatcherStart)==null?void 0:N.call(e,t))},100))}),await new Promise(()=>{})}function ue(t,e,n=new Set,o=new Set){if(o.has(t)||n.has(t))return n;if(o.add(t),t in e.filesMap)return n.add(t),n;let r=process.__vite_node__.server.moduleGraph.getModuleById(t);return r&&r.importers.forEach(s=>{s.id&&ue(s.id,e,n,o)}),n}if(!process.__vite_node__||!process.__vitest__)throw new Error("Vitest can only run in vite-node environment, please use the CLI to start the process");var Qe=process.__vite_node__.server.config.test||{},Xe=process.__vitest__.options||{},Ze=x(x({},Xe),Qe);await he(Ze);var et=setTimeout(()=>{process.exit()},500);et.unref();
@@ -1,6 +1,56 @@
1
1
  import { Awaitable } from '@antfu/utils';
2
- import { SnapshotManager } from './integrations/chai/snapshot/manager';
3
- export interface UserOptions {
2
+ import { SnapshotStateType, SnapshotResolver } from 'jest-snapshot';
3
+ import { SnapshotStateOptions } from 'jest-snapshot/build/State';
4
+
5
+ interface UncheckedSnapshot {
6
+ filePath: string;
7
+ keys: Array<string>;
8
+ }
9
+ interface SnapshotSummary {
10
+ added: number;
11
+ didUpdate: boolean;
12
+ failure: boolean;
13
+ filesAdded: number;
14
+ filesRemoved: number;
15
+ filesRemovedList: Array<string>;
16
+ filesUnmatched: number;
17
+ filesUpdated: number;
18
+ matched: number;
19
+ total: number;
20
+ unchecked: number;
21
+ uncheckedKeysByFile: Array<UncheckedSnapshot>;
22
+ unmatched: number;
23
+ updated: number;
24
+ }
25
+
26
+ interface Context {
27
+ file: string;
28
+ title?: string;
29
+ fullTitle?: string;
30
+ }
31
+ declare class SnapshotManager {
32
+ snapshotState: SnapshotStateType | null;
33
+ snapshotSummary: SnapshotSummary;
34
+ snapshotOptions: SnapshotStateOptions;
35
+ context: Context | null;
36
+ testFile: string;
37
+ snapshotResolver: SnapshotResolver | null;
38
+ rootDir: string;
39
+ constructor({ rootDir, update, snapshotResolver, }: {
40
+ rootDir: string;
41
+ update?: boolean;
42
+ snapshotResolver?: SnapshotResolver | null;
43
+ });
44
+ onFileChanged(): void;
45
+ setTask(task: Task): void;
46
+ setContext(context: Context): void;
47
+ assert(received: unknown, message: string): void;
48
+ clear(): void;
49
+ saveSnap(): void;
50
+ report(): string[] | undefined;
51
+ }
52
+
53
+ interface UserOptions {
4
54
  /**
5
55
  * Include globs for test files
6
56
  *
@@ -58,16 +108,16 @@ export interface UserOptions {
58
108
  */
59
109
  reporter?: Reporter;
60
110
  }
61
- export interface ResolvedConfig extends Required<UserOptions> {
111
+ interface ResolvedConfig extends Required<UserOptions> {
62
112
  filters?: string[];
63
113
  config?: string;
64
114
  }
65
- export declare type RunMode = 'run' | 'skip' | 'only' | 'todo';
66
- export declare type TaskState = RunMode | 'pass' | 'fail';
67
- export interface ConcurrentOptions {
115
+ declare type RunMode = 'run' | 'skip' | 'only' | 'todo';
116
+ declare type TaskState = RunMode | 'pass' | 'fail';
117
+ interface ConcurrentOptions {
68
118
  timeout: number;
69
119
  }
70
- export interface Task {
120
+ interface Task {
71
121
  name: string;
72
122
  mode: RunMode;
73
123
  concurrent?: ConcurrentOptions;
@@ -77,7 +127,7 @@ export interface Task {
77
127
  state?: TaskState;
78
128
  error?: unknown;
79
129
  }
80
- export declare type TestFunction = () => Awaitable<void>;
130
+ declare type TestFunction = () => Awaitable<void>;
81
131
  interface ConcurrentCollector {
82
132
  (name: string, fn: TestFunction, timeout?: number): void;
83
133
  only: (name: string, fn: TestFunction, timeout?: number) => void;
@@ -96,15 +146,15 @@ interface TodoCollector {
96
146
  (name: string): void;
97
147
  concurrent: (name: string) => void;
98
148
  }
99
- export interface TestCollector {
149
+ interface TestCollector {
100
150
  (name: string, fn: TestFunction): void;
101
151
  concurrent: ConcurrentCollector;
102
152
  only: OnlyCollector;
103
153
  skip: SkipCollector;
104
154
  todo: TodoCollector;
105
155
  }
106
- export declare type HookListener<T extends any[]> = (...args: T) => Awaitable<void>;
107
- export interface Suite {
156
+ declare type HookListener<T extends any[]> = (...args: T) => Awaitable<void>;
157
+ interface Suite {
108
158
  name: string;
109
159
  mode: RunMode;
110
160
  tasks: Task[];
@@ -118,7 +168,7 @@ export interface Suite {
118
168
  afterEach: HookListener<[Task, Suite]>[];
119
169
  };
120
170
  }
121
- export interface SuiteCollector {
171
+ interface SuiteCollector {
122
172
  readonly name: string;
123
173
  readonly mode: RunMode;
124
174
  test: TestCollector;
@@ -126,14 +176,14 @@ export interface SuiteCollector {
126
176
  clear: () => void;
127
177
  on: <T extends keyof Suite['hooks']>(name: T, ...fn: Suite['hooks'][T]) => void;
128
178
  }
129
- export declare type TestFactory = (test: (name: string, fn: TestFunction) => void) => Awaitable<void>;
130
- export interface File {
179
+ declare type TestFactory = (test: (name: string, fn: TestFunction) => void) => Awaitable<void>;
180
+ interface File {
131
181
  filepath: string;
132
182
  suites: Suite[];
133
183
  collected: boolean;
134
184
  error?: unknown;
135
185
  }
136
- export interface RunnerContext {
186
+ interface RunnerContext {
137
187
  filesMap: Record<string, File>;
138
188
  files: File[];
139
189
  suites: Suite[];
@@ -142,11 +192,11 @@ export interface RunnerContext {
142
192
  reporter: Reporter;
143
193
  snapshotManager: SnapshotManager;
144
194
  }
145
- export interface GlobalContext {
195
+ interface GlobalContext {
146
196
  suites: SuiteCollector[];
147
197
  currentSuite: SuiteCollector | null;
148
198
  }
149
- export interface Reporter {
199
+ interface Reporter {
150
200
  onStart?: (config: ResolvedConfig) => Awaitable<void>;
151
201
  onCollected?: (files: File[], ctx: RunnerContext) => Awaitable<void>;
152
202
  onFinished?: (ctx: RunnerContext, files?: File[]) => Awaitable<void>;
@@ -159,4 +209,5 @@ export interface Reporter {
159
209
  onWatcherStart?: (ctx: RunnerContext) => Awaitable<void>;
160
210
  onWatcherRerun?: (files: string[], trigger: string, ctx: RunnerContext) => Awaitable<void>;
161
211
  }
162
- export {};
212
+
213
+ export { ConcurrentOptions as C, File as F, GlobalContext as G, HookListener as H, ResolvedConfig as R, SuiteCollector as S, TestFunction as T, UserOptions as U, TestFactory as a, Suite as b, RunMode as c, TaskState as d, Task as e, TestCollector as f, RunnerContext as g, Reporter as h };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "vitest",
3
- "version": "0.0.35",
3
+ "version": "0.0.36",
4
4
  "description": "A blazing fast unit test framework powered by Vite",
5
5
  "keywords": [
6
6
  "vite",
@@ -8,6 +8,9 @@
8
8
  "test",
9
9
  "jest"
10
10
  ],
11
+ "engines": {
12
+ "node": ">=16.0.0"
13
+ },
11
14
  "homepage": "https://github.com/antfu/vitest#readme",
12
15
  "bugs": {
13
16
  "url": "https://github.com/antfu/vitest/issues"
@@ -40,7 +43,8 @@
40
43
  ],
41
44
  "scripts": {
42
45
  "prepare": "esmo scripts/generate-types.ts",
43
- "build": "rimraf dist && tsc -p src/tsconfig.json",
46
+ "build": "tsup --dts --minify",
47
+ "dev": "tsup --watch src",
44
48
  "lint": "eslint \"{src,test}/**/*.ts\"",
45
49
  "prepublishOnly": "nr build",
46
50
  "release": "bumpp --commit --push --tag && esmo scripts/publish.ts",
@@ -48,8 +52,7 @@
48
52
  "test:core": "node bin/vitest.mjs --dev -r test/core",
49
53
  "test:vue": "node bin/vitest.mjs --dev -r test/vue",
50
54
  "test:react": "node bin/vitest.mjs --dev -r test/react",
51
- "coverage": "node bin/vitest.mjs --dev -r test/core --coverage",
52
- "watch": "tsc -p src/tsconfig.json --watch"
55
+ "coverage": "node bin/vitest.mjs --dev -r test/core --coverage"
53
56
  },
54
57
  "dependencies": {
55
58
  "@antfu/utils": "^0.3.0",
@@ -91,6 +94,7 @@
91
94
  "esno": "^0.12.1",
92
95
  "npm-run-all": "^4.1.5",
93
96
  "rimraf": "^3.0.2",
97
+ "tsup": "^5.10.3",
94
98
  "typescript": "^4.5.2",
95
99
  "vite": "^2.7.1"
96
100
  }
@@ -1,4 +0,0 @@
1
- export declare const defaultIncludes: string[];
2
- export declare const defaultExcludes: string[];
3
- export declare const globalApis: string[];
4
- export declare const defaultConcurrentTimeout = 5000;
package/dist/constants.js DELETED
@@ -1,24 +0,0 @@
1
- export const defaultIncludes = ['**/*.{test,spec}.{js,mjs,cjs,ts,mts,cts,jsx,tsx}'];
2
- export const defaultExcludes = ['**/node_modules/**', '**/dist/**'];
3
- export const globalApis = [
4
- // suite
5
- 'suite',
6
- 'test',
7
- 'describe',
8
- 'it',
9
- // chai
10
- 'chai',
11
- 'expect',
12
- 'assert',
13
- // sinon
14
- 'sinon',
15
- 'spy',
16
- 'mock',
17
- 'stub',
18
- // hooks
19
- 'beforeAll',
20
- 'afterAll',
21
- 'beforeEach',
22
- 'afterEach',
23
- ];
24
- export const defaultConcurrentTimeout = 5000;
package/dist/context.d.ts DELETED
@@ -1,2 +0,0 @@
1
- import { GlobalContext } from './types';
2
- export declare const context: GlobalContext;
package/dist/context.js DELETED
@@ -1,4 +0,0 @@
1
- export const context = {
2
- suites: [],
3
- currentSuite: null,
4
- };
@@ -1,3 +0,0 @@
1
- import chai from 'chai';
2
- export { assert, should, expect } from 'chai';
3
- export { chai };
@@ -1,3 +0,0 @@
1
- import chai from 'chai';
2
- export { assert, should, expect } from 'chai';
3
- export { chai };
@@ -1,2 +0,0 @@
1
- import { ChaiPlugin } from './types';
2
- export declare function JestChaiExpect(): ChaiPlugin;