vitest 0.0.51 → 0.0.55
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.gh.md +23 -10
- package/dist/{chunk-3SFPYX4Z.js → chunk-2AYT2TPD.js} +1 -1
- package/dist/chunk-2PVIVCXM.js +1 -0
- package/dist/chunk-4STHXS4C.js +1 -0
- package/dist/{chunk-6IXNQZKF.js → chunk-64PJVUUV.js} +1 -1
- package/dist/chunk-OGVCGRFA.js +1 -0
- package/dist/{chunk-O4FYQN5G.js → chunk-P3CD745R.js} +1 -1
- package/dist/global-JR77FFGO.js +1 -0
- package/dist/{happy-dom-57PK5RJB.js → happy-dom-EZVJENUI.js} +1 -1
- package/dist/index.d.ts +38 -27
- package/dist/index.js +1 -1
- package/dist/{jsdom-3T4EXDYB.js → jsdom-VHB26LUJ.js} +1 -1
- package/dist/node/cli.d.ts +4 -14
- package/dist/node/cli.js +22 -7
- package/dist/node/worker.d.ts +24 -0
- package/dist/node/worker.js +4 -0
- package/dist/runtime/entry.d.ts +9 -0
- package/dist/runtime/entry.js +1 -0
- package/dist/{types-4b0e87eb.d.ts → types-1c9fc1d5.d.ts} +81 -53
- package/package.json +3 -1
- package/dist/chunk-HKVZR3WA.js +0 -1
- package/dist/chunk-R5NXUB2R.js +0 -1
- package/dist/global-M3UGZDVG.js +0 -1
- package/dist/node/entry.d.ts +0 -1
- package/dist/node/entry.js +0 -20
package/README.gh.md
CHANGED
|
@@ -25,17 +25,16 @@ A blazing fast unit test framework powered by Vite.
|
|
|
25
25
|
|
|
26
26
|
- [Vite](https://vitejs.dev/)'s config, transformers, resolvers, and plugins. Use the same setup from your app!
|
|
27
27
|
- [Jest Snapshot](https://jestjs.io/docs/snapshot-testing)
|
|
28
|
-
- [Chai](https://www.chaijs.com/) built-in for assertions, with [
|
|
29
|
-
- [Smart watch mode](#watch-mode),
|
|
30
|
-
- [
|
|
31
|
-
- [Sinon](https://sinonjs.org/) built-in for mocking
|
|
28
|
+
- [Chai](https://www.chaijs.com/) built-in for assertions, with [Jest expect](https://jestjs.io/docs/expect) compatible APIs.
|
|
29
|
+
- [Smart & instant watch mode](#watch-mode), like HMR for tests!
|
|
30
|
+
- [Native code coverage](#coverage) via [c8](https://github.com/bcoe/c8)
|
|
31
|
+
- [Sinon](https://sinonjs.org/) built-in for mocking, stubbing, and spies.
|
|
32
32
|
- [JSDOM](https://github.com/jsdom/jsdom) and [happy-dom](https://github.com/capricorn86/happy-dom) built-in for DOM and browser API mocking
|
|
33
|
-
- Components testing ([Vue
|
|
34
|
-
-
|
|
35
|
-
- ESM
|
|
33
|
+
- Components testing ([Vue](./test/vue), [React](./test/react), [Lit](./test/lit), [Vitesse](./test/vitesse))
|
|
34
|
+
- Workers multi-threading via [Piscina](https://github.com/piscinajs/piscina)
|
|
35
|
+
- ESM first, top level await
|
|
36
36
|
- Out-of-box TypeScript / JSX support
|
|
37
|
-
-
|
|
38
|
-
- Concurrent Tests
|
|
37
|
+
- Filtering, timeouts, concurrent for suite and tests
|
|
39
38
|
|
|
40
39
|
```ts
|
|
41
40
|
import { it, describe, expect, assert } from 'vitest'
|
|
@@ -135,7 +134,7 @@ export default defineConfig({
|
|
|
135
134
|
plugins: [
|
|
136
135
|
AutoImport({
|
|
137
136
|
imports: ['vitest'],
|
|
138
|
-
dts: true //
|
|
137
|
+
dts: true // generate TypeScript declaration
|
|
139
138
|
})
|
|
140
139
|
]
|
|
141
140
|
})
|
|
@@ -219,6 +218,20 @@ basic.test.ts
|
|
|
219
218
|
basic-foo.test.ts
|
|
220
219
|
```
|
|
221
220
|
|
|
221
|
+
### Specifying a Timeout
|
|
222
|
+
|
|
223
|
+
You can optionally pass a timeout in milliseconds as third argument to tests. The default is 5 seconds.
|
|
224
|
+
|
|
225
|
+
```ts
|
|
226
|
+
test('name', async() => { ... }, 1000)
|
|
227
|
+
```
|
|
228
|
+
|
|
229
|
+
Hooks also can receive a timeout, with the same 5 seconds default.
|
|
230
|
+
|
|
231
|
+
```ts
|
|
232
|
+
beforeAll( async() => { ... }, 1000)
|
|
233
|
+
```
|
|
234
|
+
|
|
222
235
|
### Skipping suites and tests
|
|
223
236
|
|
|
224
237
|
Use `.skip` to avoid running certain suites or tests
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{init_esm_shims}from"./chunk-
|
|
1
|
+
import{init_esm_shims}from"./chunk-64PJVUUV.js";init_esm_shims();var LIVING_KEYS=["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"],OTHER_KEYS=["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"],KEYS=LIVING_KEYS.concat(OTHER_KEYS);export{KEYS};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{init_esm_shims}from"./chunk-64PJVUUV.js";init_esm_shims();import{resolve}from"path";import{fileURLToPath}from"url";var distDir=resolve(fileURLToPath(import.meta.url),"../../dist"),defaultTestTimeout=5e3,defaultHookTimeout=5e3,defaultIncludes=["**/*.{test,spec}.{js,mjs,cjs,ts,mts,cts,jsx,tsx}"],defaultExcludes=["**/node_modules/**","**/dist/**"],globalApis=["suite","test","describe","it","chai","expect","assert","sinon","spy","mock","stub","beforeAll","afterAll","beforeEach","afterEach"];export{distDir,defaultTestTimeout,defaultHookTimeout,defaultIncludes,defaultExcludes,globalApis};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{init_esm_shims}from"./chunk-64PJVUUV.js";init_esm_shims();import{toArray}from"@antfu/utils";function partitionSuiteChildren(suite){let tasksGroup=[],tasksGroups=[];for(let c of suite.tasks)tasksGroup.length===0||c.computeMode===tasksGroup[0].computeMode?tasksGroup.push(c):(tasksGroups.push(tasksGroup),tasksGroup=[c]);return tasksGroup.length>0&&tasksGroups.push(tasksGroup),tasksGroups}function interpretOnlyMode(items){items.some(i=>i.mode==="only")&&items.forEach(i=>{i.mode==="run"?i.mode="skip":i.mode==="only"&&(i.mode="run")})}function getTests(suite){return toArray(suite).flatMap(s=>s.tasks.flatMap(c=>c.type==="test"?[c]:getTests(c)))}function getSuites(suite){return toArray(suite).flatMap(s=>s.type==="suite"?[s,...getSuites(s.tasks)]:[])}function hasTests(suite){return toArray(suite).some(s=>s.tasks.some(c=>c.type==="test"||hasTests(c)))}function hasFailed(suite){return toArray(suite).some(s=>{var _a;return((_a=s.result)==null?void 0:_a.state)==="fail"||s.type==="suite"&&hasFailed(s.tasks)})}function getNames(task){let names=[task.name],current=task;for(;(current==null?void 0:current.suite)||(current==null?void 0:current.file);)current=current.suite||current.file,(current==null?void 0:current.name)&&names.unshift(current.name);return names}init_esm_shims();import Test from"@jest/test-result";var{makeEmptyAggregatedTestResult}=Test,emptySummary=options=>{let summary=makeEmptyAggregatedTestResult().snapshot;return summary.didUpdate=options.updateSnapshot==="all",summary},packSnapshotState=(filepath,snapshotState)=>{let snapshot={filepath,added:0,fileDeleted:!1,matched:0,unchecked:0,uncheckedKeys:[],unmatched:0,updated:0},uncheckedCount=snapshotState.getUncheckedCount(),uncheckedKeys=snapshotState.getUncheckedKeys();uncheckedCount&&snapshotState.removeUncheckedKeys();let status=snapshotState.save();return snapshot.fileDeleted=status.deleted,snapshot.added=snapshotState.added,snapshot.matched=snapshotState.matched,snapshot.unmatched=snapshotState.unmatched,snapshot.updated=snapshotState.updated,snapshot.unchecked=status.deleted?0:uncheckedCount,snapshot.uncheckedKeys=Array.from(uncheckedKeys),snapshot},addSnapshotResult=(snapshotSummary,snapshotResult)=>{snapshotResult.added&&snapshotSummary.filesAdded++,snapshotResult.fileDeleted&&snapshotSummary.filesRemoved++,snapshotResult.unmatched&&snapshotSummary.filesUnmatched++,snapshotResult.updated&&snapshotSummary.filesUpdated++,snapshotSummary.added+=snapshotResult.added,snapshotSummary.matched+=snapshotResult.matched,snapshotSummary.unchecked+=snapshotResult.unchecked,snapshotResult.uncheckedKeys&&snapshotResult.uncheckedKeys.length>0&&snapshotSummary.uncheckedKeysByFile.push({filePath:snapshotResult.filepath,keys:snapshotResult.uncheckedKeys}),snapshotSummary.unmatched+=snapshotResult.unmatched,snapshotSummary.updated+=snapshotResult.updated,snapshotSummary.total+=snapshotResult.added+snapshotResult.matched+snapshotResult.unmatched+snapshotResult.updated};export{partitionSuiteChildren,interpretOnlyMode,getTests,getSuites,hasTests,hasFailed,getNames,emptySummary,packSnapshotState,addSnapshotResult};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var __create=Object.create;var __defProp=Object.defineProperty,__defProps=Object.defineProperties,__getOwnPropDesc=Object.getOwnPropertyDescriptor,__getOwnPropDescs=Object.getOwnPropertyDescriptors,__getOwnPropNames=Object.getOwnPropertyNames,__getOwnPropSymbols=Object.getOwnPropertySymbols,__getProtoOf=Object.getPrototypeOf,__hasOwnProp=Object.prototype.hasOwnProperty,__propIsEnum=Object.prototype.propertyIsEnumerable;var __defNormalProp=(obj,key,value)=>key in obj?__defProp(obj,key,{enumerable:!0,configurable:!0,writable:!0,value}):obj[key]=value,__spreadValues=(a,b)=>{for(var prop in b||(b={}))__hasOwnProp.call(b,prop)&&__defNormalProp(a,prop,b[prop]);if(__getOwnPropSymbols)for(var prop of __getOwnPropSymbols(b))__propIsEnum.call(b,prop)&&__defNormalProp(a,prop,b[prop]);return a},__spreadProps=(a,b)=>__defProps(a,__getOwnPropDescs(b)),__markAsModule=target=>__defProp(target,"__esModule",{value:!0});var __esm=(fn,res)=>function(){return fn&&(res=(0,fn[Object.keys(fn)[0]])(fn=0)),res};var __commonJS=(cb,mod)=>function(){return mod||(0,cb[Object.keys(cb)[0]])((mod={exports:{}}).exports,mod),mod.exports};var __export=(target,all)=>{__markAsModule(target);for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0})},__reExport=(target,module,desc)=>{if(module&&typeof module=="object"||typeof module=="function")for(let key of __getOwnPropNames(module))!__hasOwnProp.call(target,key)&&key!=="default"&&__defProp(target,key,{get:()=>module[key],enumerable:!(desc=__getOwnPropDesc(module,key))||desc.enumerable});return target},__toModule=module=>__reExport(__markAsModule(__defProp(module!=null?__create(__getProtoOf(module)):{},"default",module&&module.__esModule&&"default"in module?{get:()=>module.default,enumerable:!0}:{value:module,enumerable:!0})),module);import{fileURLToPath}from"url";import path from"path";var __filename,__dirname,init_esm_shims=__esm({"node_modules/.pnpm/tsup@5.10.3_typescript@4.5.2/node_modules/tsup/assets/esm_shims.js"(){__filename=fileURLToPath(import.meta.url),__dirname=path.dirname(__filename)}});export{__spreadValues,__spreadProps,__commonJS,__export,__toModule,
|
|
1
|
+
var __create=Object.create;var __defProp=Object.defineProperty,__defProps=Object.defineProperties,__getOwnPropDesc=Object.getOwnPropertyDescriptor,__getOwnPropDescs=Object.getOwnPropertyDescriptors,__getOwnPropNames=Object.getOwnPropertyNames,__getOwnPropSymbols=Object.getOwnPropertySymbols,__getProtoOf=Object.getPrototypeOf,__hasOwnProp=Object.prototype.hasOwnProperty,__propIsEnum=Object.prototype.propertyIsEnumerable;var __defNormalProp=(obj,key,value)=>key in obj?__defProp(obj,key,{enumerable:!0,configurable:!0,writable:!0,value}):obj[key]=value,__spreadValues=(a,b)=>{for(var prop in b||(b={}))__hasOwnProp.call(b,prop)&&__defNormalProp(a,prop,b[prop]);if(__getOwnPropSymbols)for(var prop of __getOwnPropSymbols(b))__propIsEnum.call(b,prop)&&__defNormalProp(a,prop,b[prop]);return a},__spreadProps=(a,b)=>__defProps(a,__getOwnPropDescs(b)),__markAsModule=target=>__defProp(target,"__esModule",{value:!0});var __esm=(fn,res)=>function(){return fn&&(res=(0,fn[Object.keys(fn)[0]])(fn=0)),res};var __commonJS=(cb,mod)=>function(){return mod||(0,cb[Object.keys(cb)[0]])((mod={exports:{}}).exports,mod),mod.exports};var __export=(target,all)=>{__markAsModule(target);for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0})},__reExport=(target,module,desc)=>{if(module&&typeof module=="object"||typeof module=="function")for(let key of __getOwnPropNames(module))!__hasOwnProp.call(target,key)&&key!=="default"&&__defProp(target,key,{get:()=>module[key],enumerable:!(desc=__getOwnPropDesc(module,key))||desc.enumerable});return target},__toModule=module=>__reExport(__markAsModule(__defProp(module!=null?__create(__getProtoOf(module)):{},"default",module&&module.__esModule&&"default"in module?{get:()=>module.default,enumerable:!0}:{value:module,enumerable:!0})),module);import{fileURLToPath}from"url";import path from"path";var __filename,__dirname,init_esm_shims=__esm({"node_modules/.pnpm/tsup@5.10.3_typescript@4.5.2/node_modules/tsup/assets/esm_shims.js"(){__filename=fileURLToPath(import.meta.url),__dirname=path.dirname(__filename)}});export{__spreadValues,__spreadProps,__commonJS,__export,__toModule,init_esm_shims};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{defaultHookTimeout,defaultTestTimeout}from"./chunk-2PVIVCXM.js";import{init_esm_shims}from"./chunk-64PJVUUV.js";init_esm_shims();import{nanoid}from"nanoid";init_esm_shims();var context={tasks:[],currentSuite:null};init_esm_shims();var fnMap=new WeakMap,hooksMap=new WeakMap;function setFn(key,fn){fnMap.set(key,fn)}function getFn(key){return fnMap.get(key)}function setHooks(key,hooks){hooksMap.set(key,hooks)}function getHooks(key){return hooksMap.get(key)}var suite=createSuite(),defaultSuite=suite("");function getCurrentSuite(){return context.currentSuite||defaultSuite}function createSuiteHooks(){return{beforeAll:[],afterAll:[],beforeEach:[],afterEach:[]}}function createSuiteCollector(name,factory=()=>{},mode,suiteComputeMode){var _a;let tasks=[],factoryQueue=[],suite2;initSuite();let test2=createTestCollector((name2,fn,mode2,computeMode)=>{let test3={id:nanoid(),type:"test",name:name2,mode:mode2,computeMode:computeMode??suiteComputeMode??"serial"};setFn(test3,fn),tasks.push(test3)}),collector={type:"collector",name,mode,test:test2,tasks,collect,clear,on:addHook};function addHook(name2,...fn){getHooks(suite2)[name2].push(...fn)}function initSuite(){suite2={id:nanoid(),type:"suite",computeMode:"serial",name,mode,tasks:[]},setHooks(suite2,createSuiteHooks())}function clear(){tasks.length=0,factoryQueue.length=0,initSuite()}async function collect(file){if(factoryQueue.length=0,factory){let prev=context.currentSuite;context.currentSuite=collector,await factory(test2),context.currentSuite=prev}let allChildren=await Promise.all([...factoryQueue,...tasks].map(i=>i.type==="collector"?i.collect(file):i));return suite2.file=file,suite2.tasks=allChildren,allChildren.forEach(task=>{task.suite=suite2,file&&(task.file=file)}),suite2}return(_a=context.currentSuite)==null||_a.tasks.push(collector),collector}function createTestCollector(collectTest){function test2(name,fn,timeout){collectTest(name,withTimeout(fn,timeout),"run")}test2.concurrent=concurrent,test2.skip=skip,test2.only=only,test2.todo=todo;function concurrent(name,fn,timeout){collectTest(name,withTimeout(fn,timeout),"run","concurrent")}concurrent.skip=(name,fn,timeout)=>collectTest(name,withTimeout(fn,timeout),"skip","concurrent"),concurrent.only=(name,fn,timeout)=>collectTest(name,withTimeout(fn,timeout),"only","concurrent"),concurrent.todo=todo;function skip(name,fn,timeout){collectTest(name,withTimeout(fn,timeout),"skip")}skip.concurrent=concurrent.skip;function only(name,fn,timeout){collectTest(name,withTimeout(fn,timeout),"only")}only.concurrent=concurrent.only;function todo(name){collectTest(name,()=>{},"todo")}return todo.concurrent=todo,test2}var test=function(){function test2(name,fn,timeout){return getCurrentSuite().test(name,fn,timeout)}function concurrent(name,fn,timeout){return getCurrentSuite().test.concurrent(name,fn,timeout)}concurrent.skip=(name,fn,timeout)=>getCurrentSuite().test.concurrent.skip(name,fn,timeout),concurrent.only=(name,fn,timeout)=>getCurrentSuite().test.concurrent.only(name,fn,timeout),concurrent.todo=name=>getCurrentSuite().test.concurrent.todo(name);function skip(name,fn,timeout){return getCurrentSuite().test.skip(name,fn,timeout)}skip.concurrent=(name,fn,timeout)=>getCurrentSuite().test.skip.concurrent(name,fn,timeout);function only(name,fn,timeout){return getCurrentSuite().test.only(name,fn,timeout)}only.concurrent=(name,fn,timeout)=>getCurrentSuite().test.only.concurrent(name,fn,timeout);function todo(name){return getCurrentSuite().test.todo(name)}return todo.concurrent=name=>getCurrentSuite().test.todo.concurrent(name),test2.concurrent=concurrent,test2.skip=skip,test2.only=only,test2.todo=todo,test2}();function createSuite(){function suite2(suiteName,factory){return createSuiteCollector(suiteName,factory,"run")}function concurrent(suiteName,factory){return createSuiteCollector(suiteName,factory,"run","concurrent")}concurrent.skip=(suiteName,factory)=>createSuiteCollector(suiteName,factory,"skip","concurrent"),concurrent.only=(suiteName,factory)=>createSuiteCollector(suiteName,factory,"only","concurrent"),concurrent.todo=suiteName=>createSuiteCollector(suiteName,void 0,"todo");function skip(suiteName,factory){return createSuiteCollector(suiteName,factory,"skip")}skip.concurrent=concurrent.skip;function only(suiteName,factory){return createSuiteCollector(suiteName,factory,"only")}only.concurrent=concurrent.only;function todo(suiteName){return createSuiteCollector(suiteName,void 0,"todo")}return todo.concurrent=concurrent.todo,suite2.concurrent=concurrent,suite2.skip=skip,suite2.only=only,suite2.todo=todo,suite2}var describe=suite,it=test,beforeAll=(fn,timeout=defaultHookTimeout)=>getCurrentSuite().on("beforeAll",withTimeout(fn,timeout)),afterAll=(fn,timeout=defaultHookTimeout)=>getCurrentSuite().on("afterAll",withTimeout(fn,timeout)),beforeEach=(fn,timeout=defaultHookTimeout)=>getCurrentSuite().on("beforeEach",withTimeout(fn,timeout)),afterEach=(fn,timeout=defaultHookTimeout)=>getCurrentSuite().on("afterEach",withTimeout(fn,timeout));function clearContext(){context.tasks.length=0,defaultSuite.clear(),context.currentSuite=defaultSuite}function withTimeout(fn,timeout=defaultTestTimeout){return timeout<=0||timeout===1/0?fn:(...args)=>Promise.race([fn(...args),new Promise((resolve,reject)=>{let timer=setTimeout(()=>{clearTimeout(timer),reject(new Error(`Test timed out in ${timeout}ms.`))},timeout);timer.unref()})])}export{context,getFn,setHooks,getHooks,suite,defaultSuite,createSuiteHooks,test,describe,it,beforeAll,afterAll,beforeEach,afterEach,clearContext};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{afterAll,afterEach,beforeAll,beforeEach,clearContext,createSuiteHooks,defaultSuite,describe,it,suite,test}from"./chunk-
|
|
1
|
+
import{afterAll,afterEach,beforeAll,beforeEach,clearContext,createSuiteHooks,defaultSuite,describe,it,suite,test}from"./chunk-OGVCGRFA.js";import{__export,init_esm_shims}from"./chunk-64PJVUUV.js";var src_exports={};__export(src_exports,{afterAll:()=>afterAll,afterEach:()=>afterEach,assert:()=>assert,beforeAll:()=>beforeAll,beforeEach:()=>beforeEach,chai:()=>chai,clearContext:()=>clearContext,createSuiteHooks:()=>createSuiteHooks,defaultSuite:()=>defaultSuite,describe:()=>describe,expect:()=>expect,it:()=>it,mock:()=>mock,should:()=>should,sinon:()=>sinon,spy:()=>spy,stub:()=>stub,suite:()=>suite,test:()=>test});init_esm_shims();init_esm_shims();init_esm_shims();import chai from"chai";import{assert,should,expect}from"chai";init_esm_shims();import sinon from"sinon";var{mock,spy,stub}=sinon;sinon.fn=sinon.spy;export{chai,assert,should,expect,sinon,mock,spy,stub,src_exports};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{src_exports}from"./chunk-P3CD745R.js";import"./chunk-OGVCGRFA.js";import{globalApis}from"./chunk-2PVIVCXM.js";import{init_esm_shims}from"./chunk-64PJVUUV.js";init_esm_shims();function registerApiGlobally(){globalApis.forEach(api=>{globalThis[api]=src_exports[api]})}export{registerApiGlobally};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{KEYS}from"./chunk-
|
|
1
|
+
import{KEYS}from"./chunk-2AYT2TPD.js";import{init_esm_shims}from"./chunk-64PJVUUV.js";init_esm_shims();import{Window}from"happy-dom";function setupHappyDOM(global){let win=new Window,keys=KEYS.concat(Object.getOwnPropertyNames(win)).filter(k=>!k.startsWith("_")).filter(k=>!(k in global));for(let key of keys)global[key]=win[key];return{dom:win,restore(){win.happyDOM.cancelAsync(),keys.forEach(key=>delete global[key])}}}export{setupHappyDOM};
|
package/dist/index.d.ts
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
import
|
|
2
|
-
|
|
3
|
-
export { C as ComputeMode, F as File, G as GlobalContext, H as HookListener, l as Reporter, R as ResolvedConfig, c as RunMode, k as RunnerContext, g as Suite, S as SuiteCollector, b as SuiteHooks, i as Task, e as TaskBase, f as TaskResult, h as Test, j as TestCollector, T as TestFactory, a as TestFunction, d as TestState, U as UserOptions } from './types-4b0e87eb';
|
|
1
|
+
import { T as TestFactory, S as SuiteCollector, a as TestFunction, b as SuiteHooks, U as UserOptions } from './types-1c9fc1d5';
|
|
2
|
+
export { C as ComputeMode, F as File, G as GlobalContext, H as HookListener, M as ModuleCache, l as Reporter, R as ResolvedConfig, n as RpcCall, m as RpcMap, p as RpcPayload, o as RpcSend, c as RunMode, h as Suite, S as SuiteCollector, b as SuiteHooks, j as Task, e as TaskBase, f as TaskResult, g as TaskResultPack, d as TaskState, i as Test, k as TestCollector, T as TestFactory, a as TestFunction, U as UserOptions, V as VitestContext, W as WorkerContext } from './types-1c9fc1d5';
|
|
4
3
|
export { assert, default as chai, expect, should } from 'chai';
|
|
5
4
|
import sinon from 'sinon';
|
|
6
5
|
export { default as sinon } from 'sinon';
|
|
6
|
+
import 'worker_threads';
|
|
7
7
|
import '@antfu/utils';
|
|
8
|
-
import '
|
|
8
|
+
import 'vite';
|
|
9
9
|
import 'jest-snapshot/build/State';
|
|
10
10
|
|
|
11
11
|
declare const suite: {
|
|
@@ -37,20 +37,20 @@ declare function createSuiteHooks(): {
|
|
|
37
37
|
afterEach: never[];
|
|
38
38
|
};
|
|
39
39
|
declare const test: {
|
|
40
|
-
(name: string, fn: TestFunction): void;
|
|
40
|
+
(name: string, fn: TestFunction, timeout?: number | undefined): void;
|
|
41
41
|
concurrent: {
|
|
42
|
-
(name: string, fn: TestFunction): void;
|
|
43
|
-
skip(name: string, fn: TestFunction): void;
|
|
44
|
-
only(name: string, fn: TestFunction): void;
|
|
42
|
+
(name: string, fn: TestFunction, timeout?: number | undefined): void;
|
|
43
|
+
skip(name: string, fn: TestFunction, timeout?: number | undefined): void;
|
|
44
|
+
only(name: string, fn: TestFunction, timeout?: number | undefined): void;
|
|
45
45
|
todo(name: string): void;
|
|
46
46
|
};
|
|
47
47
|
skip: {
|
|
48
|
-
(name: string, fn: TestFunction): void;
|
|
49
|
-
concurrent(name: string, fn: TestFunction): void;
|
|
48
|
+
(name: string, fn: TestFunction, timeout?: number | undefined): void;
|
|
49
|
+
concurrent(name: string, fn: TestFunction, timeout?: number | undefined): void;
|
|
50
50
|
};
|
|
51
51
|
only: {
|
|
52
|
-
(name: string, fn: TestFunction): void;
|
|
53
|
-
concurrent(name: string, fn: TestFunction): void;
|
|
52
|
+
(name: string, fn: TestFunction, timeout?: number | undefined): void;
|
|
53
|
+
concurrent(name: string, fn: TestFunction, timeout?: number | undefined): void;
|
|
54
54
|
};
|
|
55
55
|
todo: {
|
|
56
56
|
(name: string): void;
|
|
@@ -79,30 +79,30 @@ declare const describe: {
|
|
|
79
79
|
};
|
|
80
80
|
};
|
|
81
81
|
declare const it: {
|
|
82
|
-
(name: string, fn: TestFunction): void;
|
|
82
|
+
(name: string, fn: TestFunction, timeout?: number | undefined): void;
|
|
83
83
|
concurrent: {
|
|
84
|
-
(name: string, fn: TestFunction): void;
|
|
85
|
-
skip(name: string, fn: TestFunction): void;
|
|
86
|
-
only(name: string, fn: TestFunction): void;
|
|
84
|
+
(name: string, fn: TestFunction, timeout?: number | undefined): void;
|
|
85
|
+
skip(name: string, fn: TestFunction, timeout?: number | undefined): void;
|
|
86
|
+
only(name: string, fn: TestFunction, timeout?: number | undefined): void;
|
|
87
87
|
todo(name: string): void;
|
|
88
88
|
};
|
|
89
89
|
skip: {
|
|
90
|
-
(name: string, fn: TestFunction): void;
|
|
91
|
-
concurrent(name: string, fn: TestFunction): void;
|
|
90
|
+
(name: string, fn: TestFunction, timeout?: number | undefined): void;
|
|
91
|
+
concurrent(name: string, fn: TestFunction, timeout?: number | undefined): void;
|
|
92
92
|
};
|
|
93
93
|
only: {
|
|
94
|
-
(name: string, fn: TestFunction): void;
|
|
95
|
-
concurrent(name: string, fn: TestFunction): void;
|
|
94
|
+
(name: string, fn: TestFunction, timeout?: number | undefined): void;
|
|
95
|
+
concurrent(name: string, fn: TestFunction, timeout?: number | undefined): void;
|
|
96
96
|
};
|
|
97
97
|
todo: {
|
|
98
98
|
(name: string): void;
|
|
99
99
|
concurrent(name: string): void;
|
|
100
100
|
};
|
|
101
101
|
};
|
|
102
|
-
declare const beforeAll: (fn: SuiteHooks['beforeAll'][0]) => void;
|
|
103
|
-
declare const afterAll: (fn: SuiteHooks['afterAll'][0]) => void;
|
|
104
|
-
declare const beforeEach: (fn: SuiteHooks['beforeEach'][0]) => void;
|
|
105
|
-
declare const afterEach: (fn: SuiteHooks['afterEach'][0]) => void;
|
|
102
|
+
declare const beforeAll: (fn: SuiteHooks['beforeAll'][0], timeout?: number) => void;
|
|
103
|
+
declare const afterAll: (fn: SuiteHooks['afterAll'][0], timeout?: number) => void;
|
|
104
|
+
declare const beforeEach: (fn: SuiteHooks['beforeEach'][0], timeout?: number) => void;
|
|
105
|
+
declare const afterEach: (fn: SuiteHooks['afterEach'][0], timeout?: number) => void;
|
|
106
106
|
declare function clearContext(): void;
|
|
107
107
|
|
|
108
108
|
declare const mock: sinon.SinonMockStatic;
|
|
@@ -128,6 +128,7 @@ declare global {
|
|
|
128
128
|
toMatch(expected: string | RegExp): void;
|
|
129
129
|
toMatchObject(expected: any): void;
|
|
130
130
|
toContain(item: any): void;
|
|
131
|
+
toContainEqual(item: any): void;
|
|
131
132
|
toBeTruthy(): void;
|
|
132
133
|
toBeFalsy(): void;
|
|
133
134
|
toBeNaN(): void;
|
|
@@ -135,13 +136,23 @@ declare global {
|
|
|
135
136
|
toBeNull(): void;
|
|
136
137
|
toBeDefined(): void;
|
|
137
138
|
toBeInstanceOf(c: any): void;
|
|
139
|
+
toBeCalledTimes(n: number): void;
|
|
138
140
|
toHaveBeenCalledTimes(n: number): void;
|
|
139
141
|
toHaveBeenCalledOnce(): void;
|
|
140
142
|
toHaveBeenCalled(): void;
|
|
143
|
+
toBeCalled(): void;
|
|
141
144
|
toHaveBeenCalledWith(...args: any[]): void;
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
+
toBeCalledWith(...args: any[]): void;
|
|
146
|
+
toReturn(): void;
|
|
147
|
+
toHaveReturned(): void;
|
|
148
|
+
toReturnTimes(times: number): void;
|
|
149
|
+
toHaveReturnedTimes(times: number): void;
|
|
150
|
+
toReturnWith(value: any): void;
|
|
151
|
+
toHaveReturnedWith(value: any): void;
|
|
152
|
+
toHaveLastReturnedWith(value: any): void;
|
|
153
|
+
lastReturnedWith(value: any): void;
|
|
154
|
+
toHaveNthReturnedWith(nthCall: number, value: any): void;
|
|
155
|
+
nthReturnedWith(nthCall: number, value: any): void;
|
|
145
156
|
}
|
|
146
157
|
}
|
|
147
158
|
}
|
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{assert,chai,expect,mock,should,sinon,spy,stub}from"./chunk-
|
|
1
|
+
import{assert,chai,expect,mock,should,sinon,spy,stub}from"./chunk-P3CD745R.js";import{afterAll,afterEach,beforeAll,beforeEach,clearContext,createSuiteHooks,defaultSuite,describe,it,suite,test}from"./chunk-OGVCGRFA.js";import"./chunk-2PVIVCXM.js";import"./chunk-64PJVUUV.js";export{afterAll,afterEach,assert,beforeAll,beforeEach,chai,clearContext,createSuiteHooks,defaultSuite,describe,expect,it,mock,should,sinon,spy,stub,suite,test};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{KEYS}from"./chunk-
|
|
1
|
+
import{KEYS}from"./chunk-2AYT2TPD.js";import{init_esm_shims}from"./chunk-64PJVUUV.js";init_esm_shims();import{JSDOM}from"jsdom";function setupJSDOM(global){let dom=new JSDOM("<!DOCTYPE html>",{pretendToBeVisual:!0,runScripts:"dangerously",url:"http://localhost:3000"}),keys=KEYS.concat(Object.getOwnPropertyNames(dom.window)).filter(k=>!k.startsWith("_")).filter(k=>!(k in global));for(let key of keys)global[key]=dom.window[key];return{dom,restore(){keys.forEach(key=>delete global[key])}}}export{setupJSDOM};
|
package/dist/node/cli.d.ts
CHANGED
|
@@ -1,23 +1,13 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import
|
|
1
|
+
import { V as VitestContext } from '../types-1c9fc1d5';
|
|
2
|
+
import 'worker_threads';
|
|
3
3
|
import '@antfu/utils';
|
|
4
|
-
import '
|
|
4
|
+
import 'vite';
|
|
5
5
|
import 'jest-snapshot/build/State';
|
|
6
6
|
|
|
7
|
-
interface ModuleCache {
|
|
8
|
-
promise?: Promise<any>;
|
|
9
|
-
exports?: any;
|
|
10
|
-
transformResult?: TransformResult;
|
|
11
|
-
}
|
|
12
|
-
|
|
13
7
|
declare global {
|
|
14
8
|
namespace NodeJS {
|
|
15
9
|
interface Process {
|
|
16
|
-
__vitest__:
|
|
17
|
-
config: ResolvedConfig;
|
|
18
|
-
server: ViteDevServer;
|
|
19
|
-
moduleCache: Map<string, ModuleCache>;
|
|
20
|
-
};
|
|
10
|
+
__vitest__: VitestContext;
|
|
21
11
|
}
|
|
22
12
|
}
|
|
23
13
|
}
|
package/dist/node/cli.js
CHANGED
|
@@ -1,7 +1,22 @@
|
|
|
1
|
-
import{distDir}from"../chunk-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
`)
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
1
|
+
import{addSnapshotResult,emptySummary,getNames,getSuites,getTests,hasFailed}from"../chunk-4STHXS4C.js";import{defaultExcludes,defaultIncludes,distDir}from"../chunk-2PVIVCXM.js";import{__commonJS,__spreadProps,__spreadValues,__toModule,init_esm_shims}from"../chunk-64PJVUUV.js";var require_indent_string=__commonJS({"node_modules/.pnpm/indent-string@4.0.0/node_modules/indent-string/index.js"(exports,module){init_esm_shims();"use strict";module.exports=(string,count=1,options)=>{if(options=__spreadValues({indent:" ",includeEmptyLines:!1},options),typeof string!="string")throw new TypeError(`Expected \`input\` to be a \`string\`, got \`${typeof string}\``);if(typeof count!="number")throw new TypeError(`Expected \`count\` to be a \`number\`, got \`${typeof count}\``);if(typeof options.indent!="string")throw new TypeError(`Expected \`options.indent\` to be a \`string\`, got \`${typeof options.indent}\``);if(count===0)return string;let regex=options.includeEmptyLines?/^/gm:/^(?!\s*$)/gm;return string.replace(regex,options.indent.repeat(count))}}});init_esm_shims();import sade from"sade";import c4 from"picocolors";import{install as installSourceMapSupport}from"source-map-support";var version="0.0.55";init_esm_shims();import{performance}from"perf_hooks";import{relative as relative2}from"path";import c3 from"picocolors";import figures2 from"figures";init_esm_shims();import{promises as fs,existsSync}from"fs";import c from"picocolors";import{createPatch}from"diff";import{notNullish}from"@antfu/utils";import{SourceMapConsumer}from"source-map";async function printError(error){let{server}=process.__vitest__,e=error,codeFramePrinted=!1,nearest=parseStack(e.stack||e.stackStr||"").find(stack=>server.moduleGraph.getModuleById(stack.file));if(nearest){let mod=server.moduleGraph.getModuleById(nearest.file),transformResult=mod==null?void 0:mod.ssrTransformResult,pos=await getOriginalPos(transformResult==null?void 0:transformResult.map,nearest);if(pos&&existsSync(nearest.file)){let sourceCode=await fs.readFile(nearest.file,"utf-8");console.error(`${c.red(`${c.bold(e.name||e.nameStr||"Unknown Error")}: ${e.message}`)}`),console.log(c.gray(`${nearest.file}:${pos.line}:${pos.column}`)),console.log(c.yellow(generateCodeFrame(sourceCode,pos))),codeFramePrinted=!0}}codeFramePrinted||console.error(e),e.showDiff&&console.error(c.gray(generateDiff(stringify(e.actual),stringify(e.expected))))}function getOriginalPos(map,{line,column}){return new Promise(resolve2=>{if(!map)return resolve2(null);SourceMapConsumer.with(map,null,consumer=>{let pos=consumer.originalPositionFor({line,column});pos.line!=null&&pos.column!=null?resolve2(pos):resolve2(null)})})}var splitRE=/\r?\n/;function posToNumber(source,pos){if(typeof pos=="number")return pos;let lines=source.split(splitRE),{line,column}=pos,start2=0;for(let i=0;i<line-1;i++)start2+=lines[i].length+1;return start2+column}function generateCodeFrame(source,start2=0,end,range=2){start2=posToNumber(source,start2),end=end||start2;let lines=source.split(splitRE),count=0,res=[];for(let i=0;i<lines.length;i++)if(count+=lines[i].length+1,count>=start2){for(let j=i-range;j<=i+range||end>count;j++){if(j<0||j>=lines.length)continue;let line=j+1;res.push(`${c.gray(`${line}${" ".repeat(Math.max(3-String(line).length,0))}|`)} ${lines[j]}`);let lineLength=lines[j].length;if(lineLength>200)return"";if(j===i){let pad=start2-(count-lineLength)+1,length=Math.max(1,end>count?lineLength-pad:end-start2);res.push(`${c.gray(" |")} ${" ".repeat(pad)}${"^".repeat(length)}`)}else if(j>i){if(end>count){let length=Math.max(Math.min(end-count,lineLength),1);res.push(`${c.gray(" |")} ${"^".repeat(length)}`)}count+=lineLength+1}}break}return res.join(`
|
|
2
|
+
`)}function stringify(obj){return String(obj)}var stackFnCallRE=/at (.*) \((.+):(\d+):(\d+)\)$/,stackBarePathRE=/at ()(.+):(\d+):(\d+)$/;function parseStack(stack){return stack.split(`
|
|
3
|
+
`).map(raw=>{let line=raw.trim(),match=line.match(stackFnCallRE)||line.match(stackBarePathRE);if(!match)return null;let file=match[2];return file.startsWith("file://")&&(file=file.slice(7)),{method:match[1],file:match[2],line:parseInt(match[3]),column:parseInt(match[4])}}).filter(notNullish)}function generateDiff(actual,expected){let diffSize=2048;return actual.length>diffSize&&(actual=`${actual.substring(0,diffSize)} ... Lines skipped`),expected.length>diffSize&&(expected=`${expected.substring(0,diffSize)} ... Lines skipped`),unifiedDiff(actual,expected)}function unifiedDiff(actual,expected){let indent=" ";function cleanUp(line){return line[0]==="+"?indent+c.green(`${line[0]} ${line.slice(1)}`):line[0]==="-"?indent+c.red(`${line[0]} ${line.slice(1)}`):line.match(/@@/)?"--":line.match(/\\ No newline/)?null:indent+line}let lines=createPatch("string",actual,expected).split(`
|
|
4
|
+
`).splice(5);return`
|
|
5
|
+
${indent}${c.red("- actual")}
|
|
6
|
+
${indent}${c.green("+ expected")}
|
|
7
|
+
|
|
8
|
+
${lines.map(cleanUp).filter(notBlank).join(`
|
|
9
|
+
`)}`}function notBlank(line){return typeof line!="undefined"&&line!==null}init_esm_shims();var import_indent_string=__toModule(require_indent_string());import{basename,dirname,isAbsolute,relative}from"path";import{createLogUpdate}from"log-update";import c2 from"picocolors";import figures from"figures";import cliTruncate from"cli-truncate";import stripAnsi from"strip-ansi";import elegantSpinner from"elegant-spinner";import logSymbols from"log-symbols";import{slash}from"@antfu/utils";var DURATION_LONG=300,MAX_HEIGHT=20,pointer=c2.yellow(figures.pointer),skipped=c2.yellow(figures.arrowDown),spinnerMap=new WeakMap,outputMap=new WeakMap,DOWN_ARROW=c2.gray("\u21B3 "),DOT=c2.gray("\u2022 ");function formatTestPath(root,path){var _a;isAbsolute(path)&&(path=relative(root,path));let dir=dirname(path),ext=((_a=path.match(/(\.(spec|test)\.[cm]?[tj]sx?)$/))==null?void 0:_a[0])||"",base=basename(path,ext);return slash(c2.dim(`${dir}/`)+c2.bold(base))+c2.dim(ext)}function renderSnapshotSummary(rootDir,snapshots){let summary=[];if(snapshots.added&&summary.push(c2.bold(c2.green(`${snapshots.added} written`))),snapshots.unmatched&&summary.push(c2.bold(c2.red(`${snapshots.unmatched} failed`))),snapshots.updated&&summary.push(c2.bold(c2.green(`${snapshots.updated} updated `))),snapshots.filesRemoved&&(snapshots.didUpdate?summary.push(c2.bold(c2.green(`${snapshots.filesRemoved} files removed `))):summary.push(c2.bold(c2.yellow(`${snapshots.filesRemoved} files obsolete `)))),snapshots.filesRemovedList&&snapshots.filesRemovedList.length){let[head,...tail]=snapshots.filesRemovedList;summary.push(`${DOWN_ARROW}${formatTestPath(rootDir,head)}`),tail.forEach(key=>{summary.push(` ${DOT}${formatTestPath(rootDir,key)}`)})}return snapshots.unchecked&&(snapshots.didUpdate?summary.push(c2.bold(c2.green(`${snapshots.unchecked} removed`))):summary.push(c2.bold(c2.yellow(`${snapshots.unchecked} obsolete`))),snapshots.uncheckedKeysByFile.forEach(uncheckedFile=>{summary.push(`${DOWN_ARROW}${formatTestPath(rootDir,uncheckedFile.filePath)}`),uncheckedFile.keys.forEach(key=>summary.push(` ${DOT}${key}`))})),summary}function getStateString(tasks,name="tests"){if(tasks.length===0)return c2.dim(`no ${name}`);let passed=tasks.filter(i=>{var _a;return((_a=i.result)==null?void 0:_a.state)==="pass"}),failed=tasks.filter(i=>{var _a;return((_a=i.result)==null?void 0:_a.state)==="fail"}),skipped2=tasks.filter(i=>i.mode==="skip"),todo=tasks.filter(i=>i.mode==="todo");return[failed.length?c2.bold(c2.red(`${failed.length} failed`)):null,passed.length?c2.bold(c2.green(`${passed.length} passed`)):null,skipped2.length?c2.yellow(`${skipped2.length} skipped`):null,todo.length?c2.gray(`${todo.length} todo`):null].filter(Boolean).join(c2.dim(" | "))+c2.gray(` (${tasks.length})`)}function getStateSymbol(task){if(task.mode==="skip"||task.mode==="todo")return skipped;if(!task.result)return c2.gray("\xB7");if(task.result.state==="run"){if(task.type==="suite")return pointer;let spinner=spinnerMap.get(task);return spinner||(spinner=elegantSpinner(),spinnerMap.set(task,spinner)),c2.yellow(spinner())}return task.result.state==="pass"?logSymbols.success:task.result.state==="fail"?task.type==="suite"?pointer:logSymbols.error:" "}function renderTree(tasks,level=0){var _a,_b,_c,_d;let output=[];for(let task of tasks){let delta=1,suffix=task.mode==="skip"||task.mode==="todo"?` ${c2.dim("[skipped]")}`:"",prefix=` ${getStateSymbol(task)} `;if(task.type==="suite"&&(suffix+=c2.dim(` (${getTests(task).length})`)),(_a=task.result)==null?void 0:_a.end){let duration=task.result.end-task.result.start;duration>DURATION_LONG&&(suffix+=c2.yellow(` ${Math.round(duration)}${c2.dim("ms")}`))}if(task.name?output.push((0,import_indent_string.default)(prefix+task.name+suffix,level,{indent:" "})):delta=0,((_b=task.result)==null?void 0:_b.state)!=="pass"&&outputMap.get(task)!=null){let data=outputMap.get(task);if(typeof data=="string"&&(data=stripAnsi(data.trim().split(`
|
|
10
|
+
`).filter(Boolean).pop()),data===""&&(data=void 0)),data!=null){let out=(0,import_indent_string.default)(`${figures.arrowRight} ${data}`,level,{indent:" "});output.push(` ${c2.gray(cliTruncate(out,process.stdout.columns-3))}`)}}(((_c=task.result)==null?void 0:_c.state)==="fail"||((_d=task.result)==null?void 0:_d.state)==="run")&&task.type==="suite"&&task.tasks.length>0&&(output=output.concat(renderTree(task.tasks,level+delta)))}return output.slice(0,MAX_HEIGHT).join(`
|
|
11
|
+
`)}var createRenderer=_tasks=>{let tasks=_tasks,timer,log=createLogUpdate(process.stdout);function update(){log(renderTree(tasks))}return{start(){return timer?this:(timer=setInterval(update,200),this)},update(_tasks2){return tasks=_tasks2,update(),this},async stop(){return timer&&(clearInterval(timer),timer=void 0),log.clear(),console.log(renderTree(tasks)),this}}};function getFullName(task){return getNames(task).join(c2.gray(" > "))}var isTTY=process.stdout.isTTY&&!process.env.CI,DefaultReporter=class{constructor(ctx){this.ctx=ctx;console.log(c3.green(`Running tests at ${c3.gray(this.ctx.config.root)}
|
|
12
|
+
`)),this.start=performance.now()}start=0;end=0;renderer;filters;relative(path){return relative2(this.ctx.config.root,path)}onStart(){if(isTTY){let files=this.ctx.state.getFiles(this.filters);this.renderer?this.renderer.update(files):this.renderer=createRenderer(files).start()}}onTaskUpdate(pack){var _a,_b,_c;if(isTTY)return;let task=this.ctx.state.idMap[pack[0]];task.type==="test"&&((_a=task.result)==null?void 0:_a.state)&&((_b=task.result)==null?void 0:_b.state)!=="run"&&(console.log(` ${getStateSymbol(task)} ${getFullName(task)}`),task.result.state==="fail"&&console.log(c3.red(` ${figures2.arrowRight} ${(_c=task.result.error)==null?void 0:_c.message}`)))}async onFinished(files=this.ctx.state.getFiles()){var _a,_b;this.end=performance.now(),await this.stopListRender(),console.log();let suites=getSuites(files),tests=getTests(files),failedSuites=suites.filter(i=>{var _a2;return(_a2=i.result)==null?void 0:_a2.error}),failedTests=tests.filter(i=>{var _a2;return((_a2=i.result)==null?void 0:_a2.state)==="fail"}),color=failedSuites.length||failedTests.length?c3.red:c3.green;if(failedSuites.length){console.error(c3.bold(c3.red(`
|
|
13
|
+
Failed to run ${failedSuites.length} suites:`)));for(let suite of failedSuites)console.error(c3.red(`
|
|
14
|
+
- ${getFullName(suite)}`)),await printError((_a=suite.result)==null?void 0:_a.error),console.log()}if(failedTests.length){console.error(c3.bold(c3.red(`
|
|
15
|
+
Failed Tests (${failedTests.length})`)));for(let test of failedTests)console.error(`${c3.red(`
|
|
16
|
+
${c3.inverse(" FAIL ")}`)} ${getFullName(test)}`),await printError((_b=test.result)==null?void 0:_b.error),console.log()}let executionTime=this.end-this.start,threadTime=tests.reduce((acc,test)=>{var _a2;return acc+(((_a2=test.result)==null?void 0:_a2.end)?test.result.end-test.result.start:0)},0),pad=str=>str.padEnd(13),time=time2=>Math.round(time2)+c3.dim("ms"),snapshotOutput=renderSnapshotSummary(this.ctx.config.root,this.ctx.snapshot.summary);snapshotOutput.length&&(console.log(snapshotOutput.map((t,i)=>i===0?`${pad("Snapshots")} ${t}`:`${pad("")} ${t}`).join(`
|
|
17
|
+
`)),console.log()),console.log(c3.bold(color(pad("Test Files"))),getStateString(files)),console.log(c3.bold(color(pad("Tests"))),getStateString(tests)),this.filters?console.log(pad("Time"),time(threadTime)):(console.log(pad("Thread Time"),time(threadTime)),console.log(pad("Time"),time(executionTime)+c3.gray(` (${(executionTime/threadTime*100).toFixed(2)}%)`))),console.log()}async onWatcherStart(){await this.stopListRender();let failed=getTests(this.ctx.state.getFiles()).filter(i=>{var _a;return((_a=i.result)==null?void 0:_a.state)==="fail"});failed.length?console.log(`
|
|
18
|
+
${c3.bold(c3.inverse(c3.red(" FAIL ")))}${c3.red(` ${failed.length} tests failed. Watching for file changes...`)}`):console.log(`
|
|
19
|
+
${c3.bold(c3.inverse(c3.green(" PASS ")))}${c3.green(" Watching for file changes...")}`)}async onWatcherRerun(files,trigger){await this.stopListRender(),this.filters=files,console.clear(),console.log(c3.blue("Re-running tests...")+c3.dim(` [ ${this.relative(trigger)} ]
|
|
20
|
+
`))}async stopListRender(){var _a;(_a=this.renderer)==null||_a.stop(),this.renderer=void 0,await new Promise(resolve2=>setTimeout(resolve2,100))}};init_esm_shims();var SnapshotManager=class{constructor(config){this.config=config;this.clear()}summary=void 0;clear(){this.summary=emptySummary(this.config.snapshotOptions)}add(result){addSnapshotResult(this.summary,result)}};init_esm_shims();import{resolve}from"path";import{findUp}from"find-up";import{createServer}from"vite";var configFiles=["vitest.config.ts","vitest.config.js","vitest.config.mjs","vite.config.ts","vite.config.js","vite.config.mjs"];async function initViteServer(options={}){var _a,_b,_c,_d;let{filters}=options,root=resolve(options.root||process.cwd());process.chdir(root);let configPath=options.config?resolve(root,options.config):await findUp(configFiles,{cwd:root}),resolved=__spreadValues({},options);resolved.config=configPath,resolved.root=root,resolved.filters=filters?Array.isArray(filters)?filters:[filters]:void 0;let server=await createServer({root,logLevel:"error",clearScreen:!1,configFile:resolved.config,optimizeDeps:{exclude:["vitest"]}});await server.pluginContainer.buildStart({}),Object.assign(resolved,server.config.test),resolved.depsInline=["vitest/dist","vitest/src","@vue","@vueuse","vue-demi","vue",/virtual:/,/\.ts$/,/\/esm\/.*\.js$/,/\.(es|esm|esm-browser|esm-bundler|es6).js$/,...((_b=(_a=server.config.test)==null?void 0:_a.deps)==null?void 0:_b.inline)||[]],resolved.depsExternal=[/node_modules/,...((_d=(_c=server.config.test)==null?void 0:_c.deps)==null?void 0:_d.external)||[]];let env=process.env,CI=!!env.CI,UPDATE_SNAPSHOT=resolved.update||env.UPDATE_SNAPSHOT;return resolved.snapshotOptions={updateSnapshot:CI&&!UPDATE_SNAPSHOT?"none":UPDATE_SNAPSHOT?"all":"new"},{server,config:resolved}}init_esm_shims();init_esm_shims();import{MessageChannel}from"worker_threads";import{pathToFileURL}from"url";import Piscina from"piscina";init_esm_shims();async function transformRequest(server,id){if(id.match(/\.(?:[cm]?[jt]sx?|json)$/))return await server.transformRequest(id,{ssr:!0});{let result=await server.transformRequest(id);return result?await server.ssrTransform(result.code,result.map,id):void 0}}function createWorkerPool(ctx){let piscina=new Piscina({filename:new URL("./dist/node/worker.js",pathToFileURL(distDir)).href});return{runTestFiles:async(files,invalidates)=>{await Promise.all(files.map(async file=>{let channel=new MessageChannel,port=channel.port2,workerPort=channel.port1;port.on("message",async({id,method,args=[]})=>{var _a,_b,_c,_d;async function send(fn){try{port.postMessage({id,result:await fn()})}catch(e){port.postMessage({id,error:e})}}switch(method){case"snapshotSaved":return send(()=>ctx.snapshot.add(args[0]));case"fetch":return send(()=>transformRequest(ctx.server,...args));case"onCollected":ctx.state.collectFiles(args[0]),(_b=(_a=ctx.reporter).onStart)==null||_b.call(_a,args[0].map(i=>i.filepath));return;case"onTaskUpdate":ctx.state.updateTasks([args[0]]),(_d=(_c=ctx.reporter).onTaskUpdate)==null||_d.call(_c,args[0]);return}console.error("Unhandled message",method,args)});let data={port:workerPort,config:ctx.config,files:[file],invalidates};await piscina.run(data,{transferList:[workerPort]}),port.close(),workerPort.close()}))},close:()=>piscina.destroy()}}init_esm_shims();import fg from"fast-glob";async function globTestFiles(config){var _a;let testFilepaths=await fg(config.includes||defaultIncludes,{absolute:!0,cwd:config.root,ignore:config.excludes||defaultExcludes});return((_a=config.filters)==null?void 0:_a.length)&&(testFilepaths=testFilepaths.filter(i=>config.filters.some(f=>i.includes(f)))),testFilepaths}init_esm_shims();import{slash as slash2}from"@antfu/utils";async function startWatcher(ctx,pool){var _a;let{reporter,server}=ctx;(_a=reporter.onWatcherStart)==null||_a.call(reporter);let timer,changedTests=new Set,seen=new Set;server.watcher.on("change",async id=>{id=slash2(id),getAffectedTests(ctx,id,changedTests,seen),changedTests.size!==0&&(clearTimeout(timer),timer=setTimeout(async()=>{var _a2,_b,_c;if(changedTests.size===0){seen.clear();return}ctx.state.getFiles().forEach(file=>{var _a3;((_a3=file.result)==null?void 0:_a3.state)==="fail"&&changedTests.add(file.filepath)});let invalidates=Array.from(seen),tests=Array.from(changedTests);changedTests.clear(),seen.clear(),await((_a2=reporter.onWatcherRerun)==null?void 0:_a2.call(reporter,tests,id)),await pool.runTestFiles(tests,invalidates),await((_b=reporter.onFinished)==null?void 0:_b.call(reporter,ctx.state.getFiles(tests))),await((_c=reporter.onWatcherStart)==null?void 0:_c.call(reporter))},100))}),await new Promise(()=>{})}function getAffectedTests(ctx,id,set=new Set,seen=new Set){if(seen.has(id)||set.has(id)||id.includes("/node_modules/")||id.includes("/vitest/dist/"))return set;if(seen.add(id),id in ctx.state.filesMap)return set.add(id),set;let mod=ctx.server.moduleGraph.getModuleById(id);return mod&&mod.importers.forEach(i=>{i.id&&getAffectedTests(ctx,i.id,set,seen)}),set}async function start(ctx){var _a,_b;let{config}=ctx,testFilepaths=await globTestFiles(config);if(!testFilepaths.length){console.error("No test files found"),process.exitCode=1;return}let pool=createWorkerPool(ctx);await pool.runTestFiles(testFilepaths),hasFailed(ctx.state.getFiles())&&(process.exitCode=1),await((_b=(_a=ctx.reporter).onFinished)==null?void 0:_b.call(_a,ctx.state.getFiles())),config.watch?await startWatcher(ctx,pool):await pool.close()}init_esm_shims();var StateManager=class{filesMap={};idMap={};taskFileMap=new WeakMap;getFiles(keys){return keys?keys.map(key=>this.filesMap[key]):Object.values(this.filesMap)}collectFiles(files){files.forEach(file=>{this.filesMap[file.filepath]=file,this.updateId(file)})}updateId(task){this.idMap[task.id]!==task&&(this.idMap[task.id]=task,task.type==="suite"&&task.tasks.forEach(task2=>{this.updateId(task2)}))}updateTasks(packs){for(let[id,result]of packs)this.idMap[id]&&(this.idMap[id].result=result)}};sade("vitest [filter]",!0).version(version).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("--dom","mock browser api using jsdom or happy-dom","").action(async(filters,argv)=>{process.env.VITEST="true",console.log(c4.magenta(c4.bold(`
|
|
21
|
+
Vitest is in closed beta exclusively for Sponsors`))),console.log(c4.yellow(`Learn more at https://vitest.dev
|
|
22
|
+
`));let{config,server}=await initViteServer(__spreadProps(__spreadValues({},argv),{filters})),ctx=process.__vitest__={server,config,state:new StateManager,snapshot:new SnapshotManager(config),reporter:config.reporter};installSourceMapSupport({environment:"node",hookRequire:!0,handleUncaughtExceptions:!0,retrieveSourceMap:id=>{var _a,_b;let map=(_b=(_a=ctx.server.moduleGraph.getModuleById(id))==null?void 0:_a.ssrTransformResult)==null?void 0:_b.map;return map?{url:id,map}:null}}),ctx.reporter||=new DefaultReporter(ctx);try{await start(ctx)}catch(e){throw process.exitCode=1,e}finally{config.watch||await server.close()}}).parse(process.argv);
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import '../index';
|
|
2
|
+
import { R as ResolvedConfig, n as RpcCall, o as RpcSend, W as WorkerContext } from '../types-1c9fc1d5';
|
|
3
|
+
import 'chai';
|
|
4
|
+
import 'sinon';
|
|
5
|
+
import 'worker_threads';
|
|
6
|
+
import '@antfu/utils';
|
|
7
|
+
import 'vite';
|
|
8
|
+
import 'jest-snapshot/build/State';
|
|
9
|
+
|
|
10
|
+
declare function init(ctx: WorkerContext): Promise<(files: string[], config: ResolvedConfig) => Promise<void>>;
|
|
11
|
+
declare function run(ctx: WorkerContext): Promise<void>;
|
|
12
|
+
declare global {
|
|
13
|
+
namespace NodeJS {
|
|
14
|
+
interface Process {
|
|
15
|
+
__vitest_worker__: {
|
|
16
|
+
config: ResolvedConfig;
|
|
17
|
+
rpc: RpcCall;
|
|
18
|
+
send: RpcSend;
|
|
19
|
+
};
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export { run as default, init };
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import{distDir}from"../chunk-2PVIVCXM.js";import{init_esm_shims}from"../chunk-64PJVUUV.js";init_esm_shims();import{resolve as resolve2}from"path";import{nanoid}from"nanoid";init_esm_shims();import{builtinModules,createRequire}from"module";import{fileURLToPath,pathToFileURL}from"url";import{dirname,resolve}from"path";import vm from"vm";import{isValidNodeImport}from"mlly";var isWindows=process.platform==="win32",stubRequests={"/@vite/client":{injectQuery:id=>id,createHotContext(){return{accept:()=>{},prune:()=>{}}},updateStyle(){}}};async function executeInViteNode({moduleCache:moduleCache2,root,files,fetch,inline,external}){let externaled=new Set(builtinModules),result=[];for(let file of files)result.push(await cachedRequest(`/@fs/${slash(resolve(file))}`,[]));return result;async function directRequest(id,fsPath,callstack){callstack=[...callstack,id];let request=async dep=>{var _a;if(callstack.includes(dep)){let cacheKey=toFilePath(dep,root);if(!((_a=moduleCache2.get(cacheKey))==null?void 0:_a.exports))throw new Error(`Circular dependency detected
|
|
2
|
+
Stack:
|
|
3
|
+
${[...callstack,dep].reverse().map(p=>`- ${p}`).join(`
|
|
4
|
+
`)}`);return moduleCache2.get(cacheKey).exports}return cachedRequest(dep,callstack)};if(id in stubRequests)return stubRequests[id];let result2=await fetch(id);if(!result2)throw new Error(`failed to load ${id}`);let url=pathToFileURL(fsPath).href,exports={};setCache(fsPath,{transformResult:result2,exports});let __filename2=fileURLToPath(url),context={require:createRequire(url),__filename:__filename2,__dirname:dirname(__filename2),__vite_ssr_import__:request,__vite_ssr_dynamic_import__:request,__vite_ssr_exports__:exports,__vite_ssr_exportAll__:obj=>exportAll(exports,obj),__vite_ssr_import_meta__:{url}};return await vm.runInThisContext(`async (${Object.keys(context).join(",")}) => { ${result2.code} }`,{filename:fsPath,lineOffset:0})(...Object.values(context)),exports}function setCache(id,mod){moduleCache2.has(id)?Object.assign(moduleCache2.get(id),mod):moduleCache2.set(id,mod)}async function shouldExternalize(id){for(let ex of inline)if(typeof ex=="string"){if(id.includes(`/node_modules/${ex}/`))return!1}else if(ex.test(id))return!1;for(let ex of external)if(typeof ex=="string"){if(id.includes(`/node_modules/${ex}/`))return!0}else if(ex.test(id))return!0;return id.includes("/node_modules/")&&!await isValidNodeImport(id)}async function cachedRequest(rawId,callstack){var _a,_b;let id=normalizeId(rawId);if(externaled.has(id))return import(id);let fsPath=toFilePath(id,root);if(externaled.has(fsPath)||await shouldExternalize(fsPath))return externaled.add(fsPath),fsPath.match(/^\w:\//)?import(`/${fsPath}`):import(fsPath);if((_a=moduleCache2.get(fsPath))==null?void 0:_a.promise)return(_b=moduleCache2.get(fsPath))==null?void 0:_b.promise;let promise=directRequest(id,fsPath,callstack);return setCache(fsPath,{promise}),await promise}function exportAll(exports,sourceModule){for(let key in sourceModule)if(key!=="default")try{Object.defineProperty(exports,key,{enumerable:!0,configurable:!0,get(){return sourceModule[key]}})}catch{}}}function normalizeId(id){return id&&id.startsWith("/@id/__x00__")&&(id=`\0${id.slice("/@id/__x00__".length)}`),id&&id.startsWith("/@id/")&&(id=id.slice("/@id/".length)),id.startsWith("__vite-browser-external:")&&(id=id.slice("__vite-browser-external:".length)),id.startsWith("node:")&&(id=id.slice("node:".length)),id}function toFilePath(id,root){id=slash(id);let absolute=id.startsWith("/@fs/")?id.slice(4):id.startsWith(dirname(root))?id:id.startsWith("/")?slash(resolve(root,id.slice(1))):id;return absolute.startsWith("//")&&(absolute=absolute.slice(1)),isWindows&&absolute.startsWith("/")?pathToFileURL(absolute.slice(1)).href:absolute}function slash(path){return path.replace(/\\/g,"/")}var _run,moduleCache=new Map;async function init(ctx){if(_run)return _run;let{config}=ctx;return _run=(await executeInViteNode({root:config.root,files:[resolve2(distDir,"runtime/entry.js")],fetch(id){return process.__vitest_worker__.rpc("fetch",id)},inline:config.depsInline,external:config.depsExternal,moduleCache}))[0].run,_run}async function run(ctx){let{config,port}=ctx,rpcPromiseMap=new Map;process.__vitest_worker__={config,rpc:(method,...args)=>new Promise((resolve3,reject)=>{let id=nanoid();rpcPromiseMap.set(id,{resolve:resolve3,reject}),port.postMessage({method,args,id})}),send(method,...args){port.postMessage({method,args})}},port.addListener("message",async data=>{let api=rpcPromiseMap.get(data.id);api&&(data.error?api.reject(data.error):api.resolve(data.result))});let run2=await init(ctx);return ctx.invalidates&&ctx.invalidates.forEach(i=>moduleCache.delete(i)),ctx.files.forEach(i=>moduleCache.delete(i)),run2(ctx.files,ctx.config)}export{run as default,init};
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import { R as ResolvedConfig } from '../types-1c9fc1d5';
|
|
2
|
+
import 'worker_threads';
|
|
3
|
+
import '@antfu/utils';
|
|
4
|
+
import 'vite';
|
|
5
|
+
import 'jest-snapshot/build/State';
|
|
6
|
+
|
|
7
|
+
declare function run(files: string[], config: ResolvedConfig): Promise<void>;
|
|
8
|
+
|
|
9
|
+
export { run };
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{getNames,hasFailed,hasTests,interpretOnlyMode,packSnapshotState,partitionSuiteChildren}from"../chunk-4STHXS4C.js";import{clearContext,context,createSuiteHooks,defaultSuite,getFn,getHooks,setHooks}from"../chunk-OGVCGRFA.js";import"../chunk-2PVIVCXM.js";import{init_esm_shims}from"../chunk-64PJVUUV.js";init_esm_shims();init_esm_shims();init_esm_shims();import chai from"chai";import SinonChai from"sinon-chai";import Subset from"chai-subset";init_esm_shims();init_esm_shims();import path from"path";import Snap from"jest-snapshot";import{expect}from"chai";init_esm_shims();var rpc=async(method,...args)=>{var _a;return(_a=process.__vitest_worker__)==null?void 0:_a.rpc(method,...args)},send=async(method,...args)=>{var _a;return(_a=process.__vitest_worker__)==null?void 0:_a.send(method,...args)};var{SnapshotState}=Snap,resolveSnapshotPath=testPath=>path.join(path.join(path.dirname(testPath),"__snapshots__"),`${path.basename(testPath)}.snap`),SnapshotClient=class{test;testFile="";snapshotState;setTest(test){this.test=test,this.testFile!==this.test.file.filepath&&(this.snapshotState&&this.saveSnap(),this.testFile=this.test.file.filepath,this.snapshotState=new SnapshotState(resolveSnapshotPath(this.testFile),process.__vitest_worker__.config.snapshotOptions))}clearTest(){this.test=void 0}assert(received,message){if(!this.test)throw new Error("Snapshot can't not be used outside of test");let{actual,expected,key,pass}=this.snapshotState.match({testName:getNames(this.test).slice(1).join(" > "),received,isInline:!1});pass||expect(actual.trim()).equals(expected?expected.trim():"",message||`Snapshot name: \`${key}\``)}async saveSnap(){if(!this.testFile||!this.snapshotState)return;let result=packSnapshotState(this.testFile,this.snapshotState);await rpc("snapshotSaved",result),this.testFile="",this.snapshotState=void 0}};var _client;function getSnapshotClient(){return _client||(_client=new SnapshotClient),_client}function SnapshotPlugin(){return function(chai2,utils){for(let key of["matchSnapshot","toMatchSnapshot"])utils.addMethod(chai2.Assertion.prototype,key,function(message){let expected=utils.flag(this,"object");getSnapshotClient().assert(expected,message)})}}init_esm_shims();function JestChaiExpect(){return(chai2,utils)=>{function def(name,fn){let addMethod=n=>{utils.addMethod(chai2.Assertion.prototype,n,fn)};Array.isArray(name)?name.forEach(n=>addMethod(n)):addMethod(name)}def("toEqual",function(expected){return this.eql(expected)}),def("toStrictEqual",function(expected){return this.equal(expected)}),def("toBe",function(expected){return this.equal(expected)}),def("toMatchObject",function(expected){return this.containSubset(expected)}),def("toMatch",function(expected){return typeof expected=="string"?this.include(expected):this.match(expected)}),def("toContain",function(item){return this.contain(item)}),def("toContainEqual",function(expected){let obj=utils.flag(this,"object"),index=Array.from(obj).findIndex(item=>{try{chai2.assert.deepEqual(item,expected)}catch{return!1}return!0});this.assert(index!==-1,"expected #{this} to deep equally contain #{exp}","expected #{this} to not deep equally contain #{exp}",expected)}),def("toBeTruthy",function(){let obj=utils.flag(this,"object");this.assert(Boolean(obj),"expected #{this} to be truthy","expected #{this} to not be truthy",obj)}),def("toBeFalsy",function(){let obj=utils.flag(this,"object");this.assert(!obj,"expected #{this} to be falsy","expected #{this} to not be falsy",obj)}),def("toBeNaN",function(){return this.be.NaN}),def("toBeUndefined",function(){return this.be.undefined}),def("toBeNull",function(){return this.be.null}),def("toBeDefined",function(){return this.not.be.undefined}),def("toBeInstanceOf",function(obj){return this.instanceOf(obj)}),def(["toHaveBeenCalledTimes","toBeCalledTimes"],function(number){return this.callCount(number)}),def("toHaveBeenCalledOnce",function(){return this.callCount(1)}),def(["toHaveBeenCalled","toBeCalled"],function(){return this.called}),def(["toHaveBeenCalledWith","toBeCalledWith"],function(...args){return this.calledWith(...args)}),def(["toHaveReturned","toReturn"],function(){let spy=utils.flag(this,"object"),calledAndNotThrew=spy.called&&!spy.alwaysThrew();this.assert(calledAndNotThrew,"expected spy to be successfully called at least once","expected spy not to be successfully called",calledAndNotThrew,!calledAndNotThrew)}),def(["toHaveReturnedTimes","toReturnTimes"],function(times){let successfullReturns=utils.flag(this,"object").getCalls().reduce((success,call)=>call.threw()?success:++success,0);this.assert(successfullReturns===times,`expected spy to be successfully called ${times} times`,`expected spy not to be successfully called ${times} times`,`expected number of returns: ${times}`,`recieved number of returns: ${successfullReturns}`)}),def(["toHaveReturnedWith","toReturnWith"],function(value){return this.returned(value)}),def(["toHaveLastReturnedWith","lastReturnedWith"],function(value){let spy=utils.flag(this,"object"),lastReturn=spy.lastCall.returned(value);this.assert(lastReturn,"expected last spy call to return #{exp}","expected last spy call not to return #{exp}",value,spy.lastCall.returnValue)});let ordinalOf=i=>{let j=i%10,k=i%100;return j===1&&k!==11?`${i}st`:j===2&&k!==12?`${i}nd`:j===3&&k!==13?`${i}rd`:`${i}th`};def(["toHaveNthReturnedWith","nthReturnedWith"],function(nthCall,value){let spy=utils.flag(this,"object"),isNot=utils.flag(this,"negate"),call=spy.getCall(nthCall-1),ordinalCall=`${ordinalOf(nthCall)} call`;!isNot&&call.threw()&&chai2.assert.fail(`expected ${ordinalCall} to return #{exp}, but instead it threw an error`);let nthCallReturn=call.returned(value);this.assert(nthCallReturn,`expected ${ordinalCall} spy call to return #{exp}`,`expected ${ordinalCall} spy call not to return #{exp}`,value,call.returnValue)})}}var installed=!1;async function setupChai(){installed||(chai.use(SinonChai),chai.use(JestChaiExpect()),chai.use(Subset),chai.use(SnapshotPlugin()),installed=!0)}async function setupEnv(config){if(await setupChai(),config.global&&(await import("../global-JR77FFGO.js")).registerApiGlobally(),config.dom==="happy-dom")return(await import("../happy-dom-EZVJENUI.js")).setupHappyDOM(globalThis).restore;if(config.dom)return(await import("../jsdom-VHB26LUJ.js")).setupJSDOM(globalThis).restore}init_esm_shims();import{performance as performance2}from"perf_hooks";init_esm_shims();import{basename}from"path";import{performance}from"perf_hooks";import{nanoid}from"nanoid";init_esm_shims();function processError(err){return err&&(err.stack&&(err.stackStr=String(err.stack)),err.name&&(err.nameStr=String(err.name)),err)}async function collectTests(paths){let files=[];for(let filepath of paths){let file={id:nanoid(),name:basename(filepath),type:"suite",mode:"run",computeMode:"serial",filepath,tasks:[]};setHooks(file,createSuiteHooks()),clearContext();try{await import(filepath);for(let c of[defaultSuite,...context.tasks])if(c.type==="test")file.tasks.push(c);else{let suite=await c.collect(file);(suite.name||suite.tasks.length)&&file.tasks.push(suite)}}catch(e){file.result={start:performance.now(),state:"fail",error:processError(e)}}files.push(file)}let tasks=files.reduce((tasks2,file)=>tasks2.concat(file.tasks),[]);return interpretOnlyMode(tasks),tasks.forEach(i=>{i.type==="suite"&&(i.mode==="skip"?i.tasks.forEach(c=>c.mode==="run"&&(c.mode="skip")):interpretOnlyMode(i.tasks))}),files}async function callHook(suite,name,args){await Promise.all(getHooks(suite)[name].map(fn=>fn(...args)))}function updateTask(task){return rpc("onTaskUpdate",[task.id,task.result])}async function runTest(test){if(test.mode==="run"){test.result={start:performance2.now(),state:"run"},updateTask(test),getSnapshotClient().setTest(test);try{await callHook(test.suite,"beforeEach",[test,test.suite]),await getFn(test)(),test.result.state="pass"}catch(e){test.result.state="fail",test.result.error=processError(e)}try{await callHook(test.suite,"afterEach",[test,test.suite])}catch(e){test.result.state="fail",test.result.error=processError(e)}getSnapshotClient().clearTest(),test.result.end=performance2.now(),updateTask(test)}}async function runSuite(suite){var _a;if(((_a=suite.result)==null?void 0:_a.state)!=="fail"){if(suite.result={start:performance2.now(),state:"run"},updateTask(suite),suite.mode==="skip")suite.result.state="skip";else if(suite.mode==="todo")suite.result.state="todo";else try{await callHook(suite,"beforeAll",[suite]);for(let tasksGroup of partitionSuiteChildren(suite)){let computeMode=tasksGroup[0].computeMode;if(computeMode==="serial")for(let c of tasksGroup)await runSuiteChild(c);else computeMode==="concurrent"&&await Promise.all(tasksGroup.map(c=>runSuiteChild(c)))}await callHook(suite,"afterAll",[suite])}catch(e){suite.result.state="fail",suite.result.error=processError(e)}suite.result.end=performance2.now(),suite.mode==="run"&&(hasTests(suite)?hasFailed(suite)?suite.result.state="fail":suite.result.state="pass":(suite.result.state="fail",suite.result.error||(suite.result.error=new Error(`No tests found in suite ${suite.name}`)))),updateTask(suite)}}async function runSuiteChild(c){return c.type==="test"?runTest(c):runSuite(c)}async function runSuites(suites){for(let suite of suites)await runSuite(suite)}async function startTests(paths){let files=await collectTests(paths);send("onCollected",files),await runSuites(files),await getSnapshotClient().saveSnap()}async function run(files,config){let restore=await setupEnv(config);await startTests(files),restore==null||restore()}export{run};
|
|
@@ -1,7 +1,28 @@
|
|
|
1
|
+
import { MessagePort } from 'worker_threads';
|
|
1
2
|
import { Awaitable } from '@antfu/utils';
|
|
2
|
-
import {
|
|
3
|
+
import { TransformResult, ViteDevServer } from 'vite';
|
|
3
4
|
import { SnapshotStateOptions } from 'jest-snapshot/build/State';
|
|
4
5
|
|
|
6
|
+
declare class StateManager {
|
|
7
|
+
filesMap: Record<string, File>;
|
|
8
|
+
idMap: Record<string, Task>;
|
|
9
|
+
taskFileMap: WeakMap<Task, File>;
|
|
10
|
+
getFiles(keys?: string[]): File[];
|
|
11
|
+
collectFiles(files: File[]): void;
|
|
12
|
+
updateId(task: Task): void;
|
|
13
|
+
updateTasks(packs: TaskResultPack[]): void;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
interface SnapshotResult {
|
|
17
|
+
filepath: string;
|
|
18
|
+
added: number;
|
|
19
|
+
fileDeleted: boolean;
|
|
20
|
+
matched: number;
|
|
21
|
+
unchecked: number;
|
|
22
|
+
uncheckedKeys: Array<string>;
|
|
23
|
+
unmatched: number;
|
|
24
|
+
updated: number;
|
|
25
|
+
}
|
|
5
26
|
interface UncheckedSnapshot {
|
|
6
27
|
filePath: string;
|
|
7
28
|
keys: Array<string>;
|
|
@@ -23,31 +44,12 @@ interface SnapshotSummary {
|
|
|
23
44
|
updated: number;
|
|
24
45
|
}
|
|
25
46
|
|
|
26
|
-
interface Context {
|
|
27
|
-
file: string;
|
|
28
|
-
title?: string;
|
|
29
|
-
fullTitle?: string;
|
|
30
|
-
}
|
|
31
47
|
declare class SnapshotManager {
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
ctx: 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
|
-
setTest(test: Test): void;
|
|
46
|
-
setContext(context: Context): void;
|
|
47
|
-
assert(received: unknown, message: string): void;
|
|
48
|
+
config: ResolvedConfig;
|
|
49
|
+
summary: SnapshotSummary;
|
|
50
|
+
constructor(config: ResolvedConfig);
|
|
48
51
|
clear(): void;
|
|
49
|
-
|
|
50
|
-
report(): string[] | undefined;
|
|
52
|
+
add(result: SnapshotResult): void;
|
|
51
53
|
}
|
|
52
54
|
|
|
53
55
|
interface UserOptions {
|
|
@@ -109,11 +111,13 @@ interface ResolvedConfig extends Omit<Required<UserOptions>, 'config' | 'filters
|
|
|
109
111
|
filters?: string[];
|
|
110
112
|
depsInline: (string | RegExp)[];
|
|
111
113
|
depsExternal: (string | RegExp)[];
|
|
114
|
+
snapshotOptions: SnapshotStateOptions;
|
|
112
115
|
}
|
|
113
116
|
declare type RunMode = 'run' | 'skip' | 'only' | 'todo';
|
|
114
|
-
declare type
|
|
117
|
+
declare type TaskState = RunMode | 'pass' | 'fail';
|
|
115
118
|
declare type ComputeMode = 'serial' | 'concurrent';
|
|
116
119
|
interface TaskBase {
|
|
120
|
+
id: string;
|
|
117
121
|
name: string;
|
|
118
122
|
mode: RunMode;
|
|
119
123
|
computeMode: ComputeMode;
|
|
@@ -122,11 +126,12 @@ interface TaskBase {
|
|
|
122
126
|
result?: TaskResult;
|
|
123
127
|
}
|
|
124
128
|
interface TaskResult {
|
|
125
|
-
state:
|
|
129
|
+
state: TaskState;
|
|
126
130
|
start: number;
|
|
127
131
|
end?: number;
|
|
128
132
|
error?: unknown;
|
|
129
133
|
}
|
|
134
|
+
declare type TaskResultPack = [id: string, result: TaskResult | undefined];
|
|
130
135
|
interface Suite extends TaskBase {
|
|
131
136
|
type: 'suite';
|
|
132
137
|
tasks: Task[];
|
|
@@ -136,31 +141,31 @@ interface File extends Suite {
|
|
|
136
141
|
}
|
|
137
142
|
interface Test extends TaskBase {
|
|
138
143
|
type: 'test';
|
|
139
|
-
suite: Suite;
|
|
140
144
|
result?: TaskResult;
|
|
141
145
|
}
|
|
142
146
|
declare type Task = Test | Suite | File;
|
|
143
147
|
declare type TestFunction = () => Awaitable<void>;
|
|
148
|
+
declare type TestCollectorFn = (name: string, fn: TestFunction, timeout?: number) => void;
|
|
144
149
|
interface ConcurrentCollector {
|
|
145
|
-
(name: string, fn: TestFunction): void;
|
|
146
|
-
only:
|
|
147
|
-
skip:
|
|
150
|
+
(name: string, fn: TestFunction, timeout?: number): void;
|
|
151
|
+
only: TestCollectorFn;
|
|
152
|
+
skip: TestCollectorFn;
|
|
148
153
|
todo: (name: string) => void;
|
|
149
154
|
}
|
|
150
155
|
interface OnlyCollector {
|
|
151
|
-
(name: string, fn: TestFunction): void;
|
|
152
|
-
concurrent:
|
|
156
|
+
(name: string, fn: TestFunction, timeout?: number): void;
|
|
157
|
+
concurrent: TestCollectorFn;
|
|
153
158
|
}
|
|
154
159
|
interface SkipCollector {
|
|
155
|
-
(name: string, fn: TestFunction): void;
|
|
156
|
-
concurrent:
|
|
160
|
+
(name: string, fn: TestFunction, timeout?: number): void;
|
|
161
|
+
concurrent: TestCollectorFn;
|
|
157
162
|
}
|
|
158
163
|
interface TodoCollector {
|
|
159
164
|
(name: string): void;
|
|
160
165
|
concurrent: (name: string) => void;
|
|
161
166
|
}
|
|
162
167
|
interface TestCollector {
|
|
163
|
-
(name: string, fn: TestFunction): void;
|
|
168
|
+
(name: string, fn: TestFunction, timeout?: number): void;
|
|
164
169
|
concurrent: ConcurrentCollector;
|
|
165
170
|
only: OnlyCollector;
|
|
166
171
|
skip: SkipCollector;
|
|
@@ -184,28 +189,51 @@ interface SuiteCollector {
|
|
|
184
189
|
on: <T extends keyof SuiteHooks>(name: T, ...fn: SuiteHooks[T]) => void;
|
|
185
190
|
}
|
|
186
191
|
declare type TestFactory = (test: (name: string, fn: TestFunction) => void) => Awaitable<void>;
|
|
187
|
-
interface RunnerContext {
|
|
188
|
-
filesMap: Record<string, File>;
|
|
189
|
-
files: File[];
|
|
190
|
-
tests: Test[];
|
|
191
|
-
config: ResolvedConfig;
|
|
192
|
-
reporter: Reporter;
|
|
193
|
-
snapshotManager: SnapshotManager;
|
|
194
|
-
}
|
|
195
192
|
interface GlobalContext {
|
|
196
193
|
tasks: (SuiteCollector | Test)[];
|
|
197
194
|
currentSuite: SuiteCollector | null;
|
|
198
195
|
}
|
|
199
196
|
interface Reporter {
|
|
200
|
-
onStart?: (
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
197
|
+
onStart?: (files?: string[]) => Awaitable<void>;
|
|
198
|
+
onFinished?: (files?: File[]) => Awaitable<void>;
|
|
199
|
+
onTaskUpdate?: (pack: TaskResultPack) => Awaitable<void>;
|
|
200
|
+
onWatcherStart?: () => Awaitable<void>;
|
|
201
|
+
onWatcherRerun?: (files: string[], trigger: string) => Awaitable<void>;
|
|
202
|
+
}
|
|
203
|
+
interface ModuleCache {
|
|
204
|
+
promise?: Promise<any>;
|
|
205
|
+
exports?: any;
|
|
206
|
+
transformResult?: TransformResult;
|
|
207
|
+
}
|
|
208
|
+
interface WorkerContext {
|
|
209
|
+
port: MessagePort;
|
|
210
|
+
config: ResolvedConfig;
|
|
211
|
+
files: string[];
|
|
212
|
+
invalidates?: string[];
|
|
213
|
+
}
|
|
214
|
+
interface RpcMap {
|
|
215
|
+
workerReady: [[], void];
|
|
216
|
+
fetch: [[id: string], TransformResult | null | undefined];
|
|
217
|
+
onCollected: [[files: File[]], void];
|
|
218
|
+
onFinished: [[], void];
|
|
219
|
+
onTaskUpdate: [[pack: TaskResultPack], void];
|
|
220
|
+
onWatcherStart: [[], void];
|
|
221
|
+
onWatcherRerun: [[files: string[], trigger: string], void];
|
|
222
|
+
snapshotSaved: [[snapshot: SnapshotResult], void];
|
|
223
|
+
}
|
|
224
|
+
declare type RpcCall = <T extends keyof RpcMap>(method: T, ...args: RpcMap[T][0]) => Promise<RpcMap[T][1]>;
|
|
225
|
+
declare type RpcSend = <T extends keyof RpcMap>(method: T, ...args: RpcMap[T][0]) => void;
|
|
226
|
+
declare type RpcPayload<T extends keyof RpcMap = keyof RpcMap> = {
|
|
227
|
+
id: string;
|
|
228
|
+
method: T;
|
|
229
|
+
args: RpcMap[T][0];
|
|
230
|
+
};
|
|
231
|
+
interface VitestContext {
|
|
232
|
+
config: ResolvedConfig;
|
|
233
|
+
server: ViteDevServer;
|
|
234
|
+
state: StateManager;
|
|
235
|
+
snapshot: SnapshotManager;
|
|
236
|
+
reporter: Reporter;
|
|
209
237
|
}
|
|
210
238
|
|
|
211
|
-
export { ComputeMode as C, File as F, GlobalContext as G, HookListener as H, ResolvedConfig as R, SuiteCollector as S, TestFactory as T, UserOptions as U, TestFunction as a, SuiteHooks as b, RunMode as c,
|
|
239
|
+
export { ComputeMode as C, File as F, GlobalContext as G, HookListener as H, ModuleCache as M, ResolvedConfig as R, SuiteCollector as S, TestFactory as T, UserOptions as U, VitestContext as V, WorkerContext as W, TestFunction as a, SuiteHooks as b, RunMode as c, TaskState as d, TaskBase as e, TaskResult as f, TaskResultPack as g, Suite as h, Test as i, Task as j, TestCollector as k, Reporter as l, RpcMap as m, RpcCall as n, RpcSend as o, RpcPayload as p };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "vitest",
|
|
3
|
-
"version": "0.0.
|
|
3
|
+
"version": "0.0.55",
|
|
4
4
|
"description": "A blazing fast unit test framework powered by Vite",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"vite",
|
|
@@ -67,10 +67,12 @@
|
|
|
67
67
|
"jest-snapshot": "^27.4.2",
|
|
68
68
|
"jest-util": "^27.4.2",
|
|
69
69
|
"jsdom": "^19.0.0",
|
|
70
|
+
"nanoid": "^3.1.30",
|
|
70
71
|
"log-symbols": "^4.1.0",
|
|
71
72
|
"log-update": "^5.0.0",
|
|
72
73
|
"mlly": "^0.3.15",
|
|
73
74
|
"picocolors": "^1.0.0",
|
|
75
|
+
"piscina": "^3.1.0",
|
|
74
76
|
"sade": "^1.7.4",
|
|
75
77
|
"sinon": "^12.0.1",
|
|
76
78
|
"sinon-chai": "^3.7.0",
|
package/dist/chunk-HKVZR3WA.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{init_esm_shims}from"./chunk-6IXNQZKF.js";init_esm_shims();import{resolve}from"path";import{fileURLToPath}from"url";var distDir=resolve(fileURLToPath(import.meta.url),"../../dist"),defaultIncludes=["**/*.{test,spec}.{js,mjs,cjs,ts,mts,cts,jsx,tsx}"],defaultExcludes=["**/node_modules/**","**/dist/**"],globalApis=["suite","test","describe","it","chai","expect","assert","sinon","spy","mock","stub","beforeAll","afterAll","beforeEach","afterEach"];export{distDir,defaultIncludes,defaultExcludes,globalApis};
|
package/dist/chunk-R5NXUB2R.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{__filename,init_esm_shims}from"./chunk-6IXNQZKF.js";init_esm_shims();init_esm_shims();var context={tasks:[],currentSuite:null};process.__vitest__||(console.warn("[vitest] Runtime is running in non-Vite environment, there might be some issues with your setup..."),console.warn("cwd: ",process.cwd()),console.warn("path:",__filename));init_esm_shims();var fnMap=new WeakMap,hooksMap=new WeakMap;function setFn(key,fn){fnMap.set(key,fn)}function getFn(key){return fnMap.get(key)}function setHooks(key,hooks){hooksMap.set(key,hooks)}function getHooks(key){return hooksMap.get(key)}var suite=createSuite(),defaultSuite=suite("");function getCurrentSuite(){return context.currentSuite||defaultSuite}function createSuiteHooks(){return{beforeAll:[],afterAll:[],beforeEach:[],afterEach:[]}}function createSuiteCollector(name,factory=()=>{},mode,suiteComputeMode){var _a;let tasks=[],factoryQueue=[],suite2;initSuite();let test2=createTestCollector((name2,fn,mode2,computeMode)=>{let test3={type:"test",name:name2,mode:mode2,computeMode:computeMode??suiteComputeMode??"serial",suite:{}};setFn(test3,fn),tasks.push(test3)}),collector={type:"collector",name,mode,test:test2,tasks,collect,clear,on:addHook};function addHook(name2,...fn){getHooks(suite2)[name2].push(...fn)}function initSuite(){suite2={type:"suite",computeMode:"serial",name,mode,tasks:[],suite:{}},setHooks(suite2,createSuiteHooks())}function clear(){tasks.length=0,factoryQueue.length=0,initSuite()}async function collect(file){if(factoryQueue.length=0,factory){let prev=context.currentSuite;context.currentSuite=collector,await factory(test2),context.currentSuite=prev}let allChildren=await Promise.all([...factoryQueue,...tasks].map(i=>i.type==="collector"?i.collect(file):i));return suite2.file=file,suite2.tasks=allChildren,allChildren.forEach(task=>{task.suite=suite2,file&&(task.file=file)}),suite2}return(_a=context.currentSuite)==null||_a.tasks.push(collector),collector}function createTestCollector(collectTest){function test2(name,fn){collectTest(name,fn,"run")}test2.concurrent=concurrent,test2.skip=skip,test2.only=only,test2.todo=todo;function concurrent(name,fn){collectTest(name,fn,"run","concurrent")}concurrent.skip=(name,fn)=>collectTest(name,fn,"skip","concurrent"),concurrent.only=(name,fn)=>collectTest(name,fn,"only","concurrent"),concurrent.todo=todo;function skip(name,fn){collectTest(name,fn,"skip")}skip.concurrent=concurrent.skip;function only(name,fn){collectTest(name,fn,"only")}only.concurrent=concurrent.only;function todo(name){collectTest(name,()=>{},"todo")}return todo.concurrent=todo,test2}var test=function(){function test2(name,fn){return getCurrentSuite().test(name,fn)}function concurrent(name,fn){return getCurrentSuite().test.concurrent(name,fn)}concurrent.skip=(name,fn)=>getCurrentSuite().test.concurrent.skip(name,fn),concurrent.only=(name,fn)=>getCurrentSuite().test.concurrent.only(name,fn),concurrent.todo=name=>getCurrentSuite().test.concurrent.todo(name);function skip(name,fn){return getCurrentSuite().test.skip(name,fn)}skip.concurrent=(name,fn)=>getCurrentSuite().test.skip.concurrent(name,fn);function only(name,fn){return getCurrentSuite().test.only(name,fn)}only.concurrent=(name,fn)=>getCurrentSuite().test.only.concurrent(name,fn);function todo(name){return getCurrentSuite().test.todo(name)}return todo.concurrent=name=>getCurrentSuite().test.todo.concurrent(name),test2.concurrent=concurrent,test2.skip=skip,test2.only=only,test2.todo=todo,test2}();function createSuite(){function suite2(suiteName,factory){return createSuiteCollector(suiteName,factory,"run")}function concurrent(suiteName,factory){return createSuiteCollector(suiteName,factory,"run","concurrent")}concurrent.skip=(suiteName,factory)=>createSuiteCollector(suiteName,factory,"skip","concurrent"),concurrent.only=(suiteName,factory)=>createSuiteCollector(suiteName,factory,"only","concurrent"),concurrent.todo=suiteName=>createSuiteCollector(suiteName,void 0,"todo");function skip(suiteName,factory){return createSuiteCollector(suiteName,factory,"skip")}skip.concurrent=concurrent.skip;function only(suiteName,factory){return createSuiteCollector(suiteName,factory,"only")}only.concurrent=concurrent.only;function todo(suiteName){return createSuiteCollector(suiteName,void 0,"todo")}return todo.concurrent=concurrent.todo,suite2.concurrent=concurrent,suite2.skip=skip,suite2.only=only,suite2.todo=todo,suite2}var describe=suite,it=test,beforeAll=fn=>getCurrentSuite().on("beforeAll",fn),afterAll=fn=>getCurrentSuite().on("afterAll",fn),beforeEach=fn=>getCurrentSuite().on("beforeEach",fn),afterEach=fn=>getCurrentSuite().on("afterEach",fn);function clearContext(){context.tasks.length=0,defaultSuite.clear(),context.currentSuite=defaultSuite}export{context,getFn,setHooks,getHooks,suite,defaultSuite,createSuiteHooks,test,describe,it,beforeAll,afterAll,beforeEach,afterEach,clearContext};
|
package/dist/global-M3UGZDVG.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{src_exports}from"./chunk-O4FYQN5G.js";import"./chunk-R5NXUB2R.js";import{globalApis}from"./chunk-HKVZR3WA.js";import{init_esm_shims}from"./chunk-6IXNQZKF.js";init_esm_shims();function registerApiGlobally(){globalApis.forEach(api=>{globalThis[api]=src_exports[api]})}export{registerApiGlobally};
|
package/dist/node/entry.d.ts
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
|
package/dist/node/entry.js
DELETED
|
@@ -1,20 +0,0 @@
|
|
|
1
|
-
import{clearContext,context,createSuiteHooks,defaultSuite,getFn,getHooks,setHooks}from"../chunk-R5NXUB2R.js";import{defaultExcludes,defaultIncludes}from"../chunk-HKVZR3WA.js";import{__commonJS,__spreadValues,__toModule,init_esm_shims}from"../chunk-6IXNQZKF.js";var require_slash=__commonJS({"node_modules/.pnpm/slash@3.0.0/node_modules/slash/index.js"(exports,module){init_esm_shims();"use strict";module.exports=path2=>{let isExtendedLengthPath=/^\\\\\?\\/.test(path2),hasNonAscii=/[^\u0000-\u0080]+/.test(path2);return isExtendedLengthPath||hasNonAscii?path2:path2.replace(/\\/g,"/")}}});var require_indent_string=__commonJS({"node_modules/.pnpm/indent-string@4.0.0/node_modules/indent-string/index.js"(exports,module){init_esm_shims();"use strict";module.exports=(string,count=1,options)=>{if(options=__spreadValues({indent:" ",includeEmptyLines:!1},options),typeof string!="string")throw new TypeError(`Expected \`input\` to be a \`string\`, got \`${typeof string}\``);if(typeof count!="number")throw new TypeError(`Expected \`count\` to be a \`number\`, got \`${typeof count}\``);if(typeof options.indent!="string")throw new TypeError(`Expected \`options.indent\` to be a \`string\`, got \`${typeof options.indent}\``);if(count===0)return string;let regex=options.includeEmptyLines?/^/gm:/^(?!\s*$)/gm;return string.replace(regex,options.indent.repeat(count))}}});init_esm_shims();init_esm_shims();import{performance as performance3}from"perf_hooks";init_esm_shims();import Snap2 from"jest-snapshot";init_esm_shims();import chai from"chai";import Snap from"jest-snapshot";init_esm_shims();import Test from"@jest/test-result";var{makeEmptyAggregatedTestResult}=Test,makeEmptySnapshotSummary=options=>{let summary=makeEmptyAggregatedTestResult().snapshot;return summary.didUpdate=options.updateSnapshot==="all",summary},packSnapshotState=snapshotState=>{let snapshot={added:0,fileDeleted:!1,matched:0,unchecked:0,uncheckedKeys:[],unmatched:0,updated:0},uncheckedCount=snapshotState.getUncheckedCount(),uncheckedKeys=snapshotState.getUncheckedKeys();uncheckedCount&&snapshotState.removeUncheckedKeys();let status=snapshotState.save();return snapshot.fileDeleted=status.deleted,snapshot.added=snapshotState.added,snapshot.matched=snapshotState.matched,snapshot.unmatched=snapshotState.unmatched,snapshot.updated=snapshotState.updated,snapshot.unchecked=status.deleted?0:uncheckedCount,snapshot.uncheckedKeys=Array.from(uncheckedKeys),snapshot},addSnapshotResult=(snapshotSummary,snapshotResult,testFilePath)=>{snapshotResult.added&&snapshotSummary.filesAdded++,snapshotResult.fileDeleted&&snapshotSummary.filesRemoved++,snapshotResult.unmatched&&snapshotSummary.filesUnmatched++,snapshotResult.updated&&snapshotSummary.filesUpdated++,snapshotSummary.added+=snapshotResult.added,snapshotSummary.matched+=snapshotResult.matched,snapshotSummary.unchecked+=snapshotResult.unchecked,snapshotResult.uncheckedKeys&&snapshotResult.uncheckedKeys.length>0&&snapshotSummary.uncheckedKeysByFile.push({filePath:testFilePath,keys:snapshotResult.uncheckedKeys}),snapshotSummary.unmatched+=snapshotResult.unmatched,snapshotSummary.updated+=snapshotResult.updated,snapshotSummary.total+=snapshotResult.added+snapshotResult.matched+snapshotResult.unmatched+snapshotResult.updated};init_esm_shims();var import_slash=__toModule(require_slash());import path,{isAbsolute}from"path";import{pluralize}from"jest-util";import c from"picocolors";var formatTestPath=(rootDir,testPath)=>{isAbsolute(testPath)&&(testPath=path.relative(rootDir,testPath));let dirname=path.dirname(testPath),basename2=path.basename(testPath);return(0,import_slash.default)(c.dim(dirname+path.sep)+c.bold(basename2))},ARROW=" \u203A ",DOWN_ARROW=" \u21B3 ",DOT=" \u2022 ",FAIL_COLOR=v=>c.bold(c.red(v)),OBSOLETE_COLOR=v=>c.bold(c.yellow(v)),SNAPSHOT_ADDED=v=>c.bold(c.green(v)),SNAPSHOT_NOTE=c.dim,SNAPSHOT_REMOVED=v=>c.bold(c.green(v)),SNAPSHOT_SUMMARY=c.bold,SNAPSHOT_UPDATED=v=>c.bold(c.green(v)),updateCommand="re-run mocha with `--update` to update them",getSnapshotSummaryOutput=(rootDir,snapshots)=>{let summary=[];if(summary.push(SNAPSHOT_SUMMARY("Snapshot Summary")),snapshots.added&&summary.push(`${SNAPSHOT_ADDED(`${ARROW+pluralize("snapshot",snapshots.added)} written `)}from ${pluralize("test suite",snapshots.filesAdded)}.`),snapshots.unmatched&&summary.push(`${FAIL_COLOR(`${ARROW}${pluralize("snapshot",snapshots.unmatched)} failed`)} from ${pluralize("test suite",snapshots.filesUnmatched)}. ${SNAPSHOT_NOTE(`Inspect your code changes or ${updateCommand} to update them.`)}`),snapshots.updated&&summary.push(`${SNAPSHOT_UPDATED(`${ARROW+pluralize("snapshot",snapshots.updated)} updated `)}from ${pluralize("test suite",snapshots.filesUpdated)}.`),snapshots.filesRemoved&&(snapshots.didUpdate?summary.push(`${SNAPSHOT_REMOVED(`${ARROW}${pluralize("snapshot file",snapshots.filesRemoved)} removed `)}from ${pluralize("test suite",snapshots.filesRemoved)}.`):summary.push(`${OBSOLETE_COLOR(`${ARROW}${pluralize("snapshot file",snapshots.filesRemoved)} obsolete `)}from ${pluralize("test suite",snapshots.filesRemoved)}. ${SNAPSHOT_NOTE(`To remove ${snapshots.filesRemoved===1?"it":"them all"}, ${updateCommand}.`)}`)),snapshots.filesRemovedList&&snapshots.filesRemovedList.length){let[head,...tail]=snapshots.filesRemovedList;summary.push(` ${DOWN_ARROW} ${DOT}${formatTestPath(rootDir,head)}`),tail.forEach(key=>{summary.push(` ${DOT}${formatTestPath(rootDir,key)}`)})}return snapshots.unchecked&&(snapshots.didUpdate?summary.push(`${SNAPSHOT_REMOVED(`${ARROW}${pluralize("snapshot",snapshots.unchecked)} removed `)}from ${pluralize("test suite",snapshots.uncheckedKeysByFile.length)}.`):summary.push(`${OBSOLETE_COLOR(`${ARROW}${pluralize("snapshot",snapshots.unchecked)} obsolete `)}from ${pluralize("test suite",snapshots.uncheckedKeysByFile.length)}. ${SNAPSHOT_NOTE(`To remove ${snapshots.unchecked===1?"it":"them all"}, ${updateCommand}.`)}`),snapshots.uncheckedKeysByFile.forEach(uncheckedFile=>{summary.push(` ${DOWN_ARROW}${formatTestPath(rootDir,uncheckedFile.filePath)}`),uncheckedFile.keys.forEach(key=>{summary.push(` ${DOT}${key}`)})})),summary};var{expect}=chai,{SnapshotState}=Snap,SnapshotManager=class{snapshotState=null;snapshotSummary;snapshotOptions;ctx=null;testFile="";snapshotResolver;rootDir;constructor({rootDir,update,snapshotResolver=null}){this.rootDir=rootDir,this.snapshotResolver=snapshotResolver;let env=process.env,CI=!!env.CI,UPDATE_SNAPSHOT=update||env.UPDATE_SNAPSHOT;this.snapshotOptions={updateSnapshot:CI&&!UPDATE_SNAPSHOT?"none":UPDATE_SNAPSHOT?"all":"new"},this.snapshotSummary=makeEmptySnapshotSummary(this.snapshotOptions)}onFileChanged(){!this.ctx||(this.snapshotState!==null&&this.saveSnap(),this.testFile=this.ctx.file,this.snapshotState=new SnapshotState(this.snapshotResolver.resolveSnapshotPath(this.testFile),this.snapshotOptions))}setTest(test){var _a;this.setContext({file:((_a=test.file)==null?void 0:_a.filepath)||test.name,title:test.name,fullTitle:[test.suite.name,test.name].filter(Boolean).join(" > ")})}setContext(context2){!context2.title||!context2.file||(this.ctx=context2,this.testFile!==context2.file&&this.onFileChanged())}assert(received,message){if(!this.snapshotState||!this.ctx)return;let{actual,expected,key,pass}=this.snapshotState.match({testName:this.ctx.fullTitle||this.ctx.title||this.ctx.file,received,isInline:!1});pass||expect(actual.trim()).equals(expected?expected.trim():"",message||`Snapshot name: \`${key}\``)}clear(){this.snapshotSummary=makeEmptySnapshotSummary(this.snapshotOptions)}saveSnap(){if(!this.testFile||!this.snapshotState)return;let packedSnapshotState=packSnapshotState(this.snapshotState);addSnapshotResult(this.snapshotSummary,packedSnapshotState,this.testFile),this.testFile="",this.snapshotState=null}report(){let outputs=getSnapshotSummaryOutput(this.rootDir,this.snapshotSummary);if(outputs.length>1)return outputs}};var{addSerializer}=Snap2,_manager;function getSnapshotManager(){return _manager}async function SnapshotPlugin(options){let{root:rootDir}=options;return _manager=new SnapshotManager({rootDir,update:options.update}),_manager.snapshotResolver=await Snap2.buildSnapshotResolver({transform:[],rootDir}),function(chai3,utils){for(let key of["matchSnapshot","toMatchSnapshot"])utils.addMethod(chai3.Assertion.prototype,key,function(message){let expected=utils.flag(this,"object");_manager.assert(expected,message)});chai3.expect.addSnapshotSerializer=addSerializer}}init_esm_shims();import{slash as slash2}from"@antfu/utils";init_esm_shims();import{basename}from"path";import{performance}from"perf_hooks";init_esm_shims();import{toArray}from"@antfu/utils";function partitionSuiteChildren(suite){let tasksGroup=[],tasksGroups=[];for(let c5 of suite.tasks)tasksGroup.length===0||c5.computeMode===tasksGroup[0].computeMode?tasksGroup.push(c5):(tasksGroups.push(tasksGroup),tasksGroup=[c5]);return tasksGroup.length>0&&tasksGroups.push(tasksGroup),tasksGroups}function interpretOnlyMode(items){items.some(i=>i.mode==="only")&&items.forEach(i=>{i.mode==="run"?i.mode="skip":i.mode==="only"&&(i.mode="run")})}function getTests(suite){return toArray(suite).flatMap(s=>s.tasks.flatMap(c5=>c5.type==="test"?[c5]:getTests(c5)))}function getTasks(tasks){return toArray(tasks).flatMap(s=>s.type==="test"?[s]:[s,...getTasks(s.tasks)])}function getSuites(suite){return toArray(suite).flatMap(s=>s.type==="suite"?[s,...getSuites(s.tasks)]:[])}function hasTests(suite){return toArray(suite).some(s=>s.tasks.some(c5=>c5.type==="test"||hasTests(c5)))}function hasFailed(suite){return toArray(suite).some(s=>s.tasks.some(c5=>{var _a;return((_a=c5.result)==null?void 0:_a.state)==="fail"}))}async function collectTests(paths){let files={};for(let filepath of paths){let file={name:basename(filepath),type:"suite",mode:"run",computeMode:"serial",filepath,tasks:[],suite:{}};setHooks(file,createSuiteHooks()),clearContext();try{await import(filepath);for(let c5 of[defaultSuite,...context.tasks])if(c5.type==="test")file.tasks.push(c5);else{let suite=await c5.collect(file);(suite.name||suite.tasks.length)&&file.tasks.push(suite)}}catch(e){file.result={start:performance.now(),state:"fail",error:e},process.exitCode=1}files[filepath]=file}let allChildren=Object.values(files).reduce((tasks,file)=>tasks.concat(file.tasks),[]);return interpretOnlyMode(allChildren),allChildren.forEach(i=>{i.type==="suite"&&(i.mode==="skip"?i.tasks.forEach(c5=>c5.mode==="run"&&(c5.mode="skip")):interpretOnlyMode(i.tasks))}),files}async function startWatcher(ctx){var _a;let{reporter,snapshotManager,filesMap}=ctx;await((_a=reporter.onWatcherStart)==null?void 0:_a.call(reporter,ctx));let timer2,changedTests=new Set,seen=new Set,{server,moduleCache}=process.__vitest__;server.watcher.on("change",async id=>{id=slash2(id),getAffectedTests(id,ctx,changedTests,seen),seen.forEach(i=>moduleCache.delete(i)),seen.clear(),changedTests.size!==0&&(clearTimeout(timer2),timer2=setTimeout(async()=>{var _a2,_b,_c,_d;if(changedTests.size===0)return;Object.values(filesMap).forEach(file=>{var _a3;((_a3=file.result)==null?void 0:_a3.state)==="fail"&&changedTests.add(file.filepath)});let paths=Array.from(changedTests);changedTests.clear(),snapshotManager.clear(),await((_a2=reporter.onWatcherRerun)==null?void 0:_a2.call(reporter,paths,id,ctx)),paths.forEach(i=>moduleCache.delete(i));let newFilesMap=await collectTests(paths);Object.assign(filesMap,newFilesMap);let files=Object.values(filesMap);(_b=reporter.onCollected)==null||_b.call(reporter,files,ctx),await runSuites(files,ctx),snapshotManager.saveSnap(),await((_c=reporter.onFinished)==null?void 0:_c.call(reporter,ctx,Object.values(newFilesMap))),await((_d=reporter.onWatcherStart)==null?void 0:_d.call(reporter,ctx))},100))}),await new Promise(()=>{})}function getAffectedTests(id,ctx,set=new Set,seen=new Set){if(seen.has(id)||set.has(id))return set;if(seen.add(id),id in ctx.filesMap)return set.add(id),set;let mod=process.__vitest__.server.moduleGraph.getModuleById(id);return mod&&mod.importers.forEach(i=>{i.id&&getAffectedTests(i.id,ctx,set,seen)}),set}init_esm_shims();import fg from"fast-glob";async function globTestFiles(config){var _a;let testFilepaths=await fg(config.includes||defaultIncludes,{absolute:!0,cwd:config.root,ignore:config.excludes||defaultExcludes});return((_a=config.filters)==null?void 0:_a.length)&&(testFilepaths=testFilepaths.filter(i=>config.filters.some(f=>i.includes(f)))),testFilepaths}init_esm_shims();init_esm_shims();import{performance as performance2}from"perf_hooks";import{relative}from"path";import c4 from"picocolors";init_esm_shims();import{promises as fs,existsSync}from"fs";import c2 from"picocolors";import{createPatch}from"diff";import{notNullish}from"@antfu/utils";import{SourceMapConsumer}from"source-map";async function printError(error){var _a;if(!(error instanceof Error)){console.error(error);return}let{moduleCache}=process.__vitest__,e=error,codeFramePrinted=!1,nearest=parseStack(e.stack||"").find(stack=>moduleCache.has(stack.file));if(nearest){let transformResult=(_a=moduleCache.get(nearest.file))==null?void 0:_a.transformResult,pos=await getOriginalPos(transformResult==null?void 0:transformResult.map,nearest);if(pos&&existsSync(nearest.file)){let sourceCode=await fs.readFile(nearest.file,"utf-8");console.error(`${c2.red(`${c2.bold(e.name)}: ${e.message}`)}`),console.log(c2.gray(`${nearest.file}:${pos.line}:${pos.column}`)),console.log(c2.yellow(generateCodeFrame(sourceCode,pos))),codeFramePrinted=!0}}codeFramePrinted||console.error(e),e.showDiff&&console.error(c2.gray(generateDiff(stringify(e.actual),stringify(e.expected))))}function getOriginalPos(map,{line,column}){return new Promise(resolve=>{if(!map)return resolve(null);SourceMapConsumer.with(map,null,consumer=>{let pos=consumer.originalPositionFor({line,column});pos.line!=null&&pos.column!=null?resolve(pos):resolve(null)})})}var splitRE=/\r?\n/;function posToNumber(source,pos){if(typeof pos=="number")return pos;let lines=source.split(splitRE),{line,column}=pos,start=0;for(let i=0;i<line-1;i++)start+=lines[i].length+1;return start+column}function generateCodeFrame(source,start=0,end,range=2){start=posToNumber(source,start),end=end||start;let lines=source.split(splitRE),count=0,res=[];for(let i=0;i<lines.length;i++)if(count+=lines[i].length+1,count>=start){for(let j=i-range;j<=i+range||end>count;j++){if(j<0||j>=lines.length)continue;let line=j+1;res.push(`${c2.gray(`${line}${" ".repeat(Math.max(3-String(line).length,0))}|`)} ${lines[j]}`);let lineLength=lines[j].length;if(lineLength>200)return"";if(j===i){let pad=start-(count-lineLength)+1,length=Math.max(1,end>count?lineLength-pad:end-start);res.push(`${c2.gray(" |")} ${" ".repeat(pad)}${"^".repeat(length)}`)}else if(j>i){if(end>count){let length=Math.max(Math.min(end-count,lineLength),1);res.push(`${c2.gray(" |")} ${"^".repeat(length)}`)}count+=lineLength+1}}break}return res.join(`
|
|
2
|
-
`)}function stringify(obj){return String(obj)}var stackFnCallRE=/at (.*) \((.+):(\d+):(\d+)\)$/,stackBarePathRE=/at ()(.+):(\d+):(\d+)$/;function parseStack(stack){return stack.split(`
|
|
3
|
-
`).map(raw=>{let line=raw.trim(),match=line.match(stackFnCallRE)||line.match(stackBarePathRE);if(!match)return null;let file=match[2];return file.startsWith("file://")&&(file=file.slice(7)),{method:match[1],file:match[2],line:parseInt(match[3]),column:parseInt(match[4])}}).filter(notNullish)}function generateDiff(actual,expected){let diffSize=2048;return actual.length>diffSize&&(actual=`${actual.substring(0,diffSize)} ... Lines skipped`),expected.length>diffSize&&(expected=`${expected.substring(0,diffSize)} ... Lines skipped`),unifiedDiff(actual,expected)}function unifiedDiff(actual,expected){let indent=" ";function cleanUp(line){return line[0]==="+"?indent+c2.green(`${line[0]} ${line.slice(1)}`):line[0]==="-"?indent+c2.red(`${line[0]} ${line.slice(1)}`):line.match(/@@/)?"--":line.match(/\\ No newline/)?null:indent+line}let lines=createPatch("string",actual,expected).split(`
|
|
4
|
-
`).splice(5);return`
|
|
5
|
-
${indent}${c2.red("- actual")}
|
|
6
|
-
${indent}${c2.green("+ expected")}
|
|
7
|
-
|
|
8
|
-
${lines.map(cleanUp).filter(notBlank).join(`
|
|
9
|
-
`)}`}function notBlank(line){return typeof line!="undefined"&&line!==null}init_esm_shims();var import_indent_string=__toModule(require_indent_string());import{createLogUpdate}from"log-update";import c3 from"picocolors";import figures from"figures";import cliTruncate from"cli-truncate";import stripAnsi from"strip-ansi";import elegantSpinner from"elegant-spinner";import logSymbols from"log-symbols";var DURATION_LONG=300,MAX_HEIGHT=20,pointer=c3.yellow(figures.pointer),skipped=c3.yellow(figures.arrowDown),spinnerMap=new WeakMap,outputMap=new WeakMap,getSymbol=task=>{if(task.mode==="skip"||task.mode==="todo")return skipped;if(!task.result)return c3.gray("\xB7");if(task.result.state==="run"){if(task.type==="suite")return pointer;let spinner=spinnerMap.get(task);return spinner||(spinner=elegantSpinner(),spinnerMap.set(task,spinner)),c3.yellow(spinner())}return task.result.state==="pass"?logSymbols.success:task.result.state==="fail"?task.type==="suite"?pointer:logSymbols.error:" "};function renderTree(tasks,level=0){var _a,_b,_c,_d;let output=[];for(let task of tasks){let delta=1,suffix=task.mode==="skip"||task.mode==="todo"?` ${c3.dim("[skipped]")}`:"",prefix=` ${getSymbol(task)} `;if(task.type==="suite"&&(suffix+=c3.dim(` (${getTests(task).length})`)),(_a=task.result)==null?void 0:_a.end){let duration=task.result.end-task.result.start;duration>DURATION_LONG&&(suffix+=c3.yellow(` ${Math.round(duration)}${c3.dim("ms")}`))}if(task.name?output.push((0,import_indent_string.default)(prefix+task.name+suffix,level,{indent:" "})):delta=0,((_b=task.result)==null?void 0:_b.state)!=="pass"&&outputMap.get(task)!=null){let data=outputMap.get(task);if(typeof data=="string"&&(data=stripAnsi(data.trim().split(`
|
|
10
|
-
`).filter(Boolean).pop()),data===""&&(data=void 0)),data!=null){let out=(0,import_indent_string.default)(`${figures.arrowRight} ${data}`,level,{indent:" "});output.push(` ${c3.gray(cliTruncate(out,process.stdout.columns-3))}`)}}(((_c=task.result)==null?void 0:_c.state)==="fail"||((_d=task.result)==null?void 0:_d.state)==="run")&&task.type==="suite"&&task.tasks.length>0&&(output=output.concat(renderTree(task.tasks,level+delta)))}return output.slice(0,MAX_HEIGHT).join(`
|
|
11
|
-
`)}var createRenderer=_tasks=>{let tasks=_tasks,timer2,log=createLogUpdate(process.stdout);function update(){log(renderTree(tasks))}return{start(){return timer2?this:(timer2=setInterval(update,200),this)},update(_tasks2){return tasks=_tasks2,update(),this},stop(){return timer2&&(clearInterval(timer2),timer2=void 0),log.clear(),console.log(renderTree(tasks)),this}}};var DefaultReporter=class{constructor(config){this.config=config}start=0;end=0;renderer;relative(path2){return relative(this.config.root,path2)}onStart(){console.log(c4.green(`Running tests under ${c4.gray(this.config.root)}
|
|
12
|
-
`)),this.start=performance2.now()}onCollected(files){var _a;(_a=this.renderer)==null||_a.stop(),this.renderer=createRenderer(files).start()}async onFinished(ctx,files=ctx.files){var _a,_b,_c;this.end=performance2.now(),await this.stopListRender(),console.log();let snapshot=ctx.snapshotManager.report();snapshot&&console.log(snapshot.join(`
|
|
13
|
-
`));let suites=getSuites(files),tests=getTests(files),failedSuites=suites.filter(i=>{var _a2;return(_a2=i.result)==null?void 0:_a2.error}),runnable=tests.filter(i=>{var _a2,_b2;return((_a2=i.result)==null?void 0:_a2.state)==="pass"||((_b2=i.result)==null?void 0:_b2.state)==="fail"}),passed=tests.filter(i=>{var _a2;return((_a2=i.result)==null?void 0:_a2.state)==="pass"}),failed=tests.filter(i=>{var _a2;return((_a2=i.result)==null?void 0:_a2.state)==="fail"}),skipped2=tests.filter(i=>i.mode==="skip"),todo=tests.filter(i=>i.mode==="todo");if(failedSuites.length){console.error(c4.bold(c4.red(`
|
|
14
|
-
Failed to run ${failedSuites.length} suites:`)));for(let suite of failedSuites)console.error(c4.red(`
|
|
15
|
-
- ${(_a=suite.file)==null?void 0:_a.filepath} > ${suite.name}`)),await printError((_b=suite.result)==null?void 0:_b.error),console.log()}if(failed.length){console.error(c4.bold(c4.red(`
|
|
16
|
-
Failed Tests (${failed.length})`)));for(let test of failed)console.error(`${c4.red(`
|
|
17
|
-
${c4.inverse(" FAIL ")}`)} ${[test.suite.name,test.name].filter(Boolean).join(" > ")}`),await printError((_c=test.result)==null?void 0:_c.error),console.log()}console.log(c4.bold(c4.green(`Passed ${passed.length} / ${runnable.length}`))),failed.length&&console.log(c4.bold(c4.red(`Failed ${failed.length} / ${runnable.length}`))),skipped2.length&&console.log(c4.yellow(`Skipped ${skipped2.length}`)),todo.length&&console.log(c4.dim(`Todo ${todo.length}`)),console.log(`Time ${(this.end-this.start).toFixed(2)}ms`)}async onWatcherStart(ctx){await this.stopListRender();let failed=getTasks(ctx.files).filter(i=>{var _a;return((_a=i.result)==null?void 0:_a.state)==="fail"});failed.length?console.log(`
|
|
18
|
-
${c4.bold(c4.inverse(c4.red(" FAIL ")))}${c4.red(` ${failed.length} tests failed. Watching for file changes...`)}`):console.log(`
|
|
19
|
-
${c4.bold(c4.inverse(c4.green(" PASS ")))}${c4.green(" Watching for file changes...")}`)}async onWatcherRerun(files,trigger){await this.stopListRender(),console.clear(),console.log(c4.blue("Re-running tests...")+c4.dim(` [ ${this.relative(trigger)} ]
|
|
20
|
-
`))}async stopListRender(){var _a;(_a=this.renderer)==null||_a.stop(),this.renderer=void 0,await new Promise(resolve=>setTimeout(resolve,100))}};init_esm_shims();init_esm_shims();import chai2 from"chai";import SinonChai from"sinon-chai";import Subset from"chai-subset";init_esm_shims();function JestChaiExpect(){return(chai3,utils)=>{let proto=chai3.Assertion.prototype;utils.addMethod(proto,"toEqual",function(expected){return this.eql(expected)}),utils.addMethod(proto,"toStrictEqual",function(expected){return this.equal(expected)}),utils.addMethod(proto,"toBe",function(expected){return this.equal(expected)}),utils.addMethod(proto,"toMatchObject",function(expected){return this.containSubset(expected)}),utils.addMethod(proto,"toMatch",function(expected){return typeof expected=="string"?this.include(expected):this.match(expected)}),utils.addMethod(proto,"toContain",function(item){return this.contain(item)}),utils.addMethod(proto,"toBeTruthy",function(){let obj=utils.flag(this,"object");this.assert(Boolean(obj),"expected #{this} to be truthy","expected #{this} to not be truthy",obj)}),utils.addMethod(proto,"toBeFalsy",function(){let obj=utils.flag(this,"object");this.assert(!obj,"expected #{this} to be falsy","expected #{this} to not be falsy",obj)}),utils.addMethod(proto,"toBeNaN",function(){return this.be.NaN}),utils.addMethod(proto,"toBeUndefined",function(){return this.be.undefined}),utils.addMethod(proto,"toBeNull",function(){return this.be.null}),utils.addMethod(proto,"toBeDefined",function(){return this.not.be.undefined}),utils.addMethod(proto,"toBeInstanceOf",function(obj){return this.instanceOf(obj)}),utils.addMethod(proto,"toHaveBeenCalledTimes",function(number){return this.callCount(number)}),utils.addMethod(proto,"toHaveBeenCalledOnce",function(){return this.callCount(1)}),utils.addMethod(proto,"toHaveBeenCalled",function(){return this.called}),utils.addMethod(proto,"toHaveBeenCalledWith",function(...args){return this.calledWith(...args)})}}async function setupChai(config){chai2.use(SinonChai),chai2.use(JestChaiExpect()),chai2.use(Subset),chai2.use(await SnapshotPlugin(config))}async function setupEnv(config){await setupChai(config),config.global&&(await import("../global-M3UGZDVG.js")).registerApiGlobally(),config.dom==="happy-dom"?(await import("../happy-dom-57PK5RJB.js")).setupHappyDOM(globalThis):config.dom&&(await import("../jsdom-3T4EXDYB.js")).setupJSDOM(globalThis)}async function setupRunner(config){return await setupEnv(config),{filesMap:{},get files(){return Object.values(this.filesMap)},get tests(){return getTests(Object.values(this.filesMap))},config,reporter:config.reporter||new DefaultReporter(config),snapshotManager:getSnapshotManager()}}async function callHook(suite,name,args){await Promise.all(getHooks(suite)[name].map(fn=>fn(...args)))}async function runTest(test,ctx){var _a,_b,_c;if(test.mode!=="run")return;let{reporter}=ctx;(_a=getSnapshotManager())==null||_a.setTest(test),await((_b=reporter.onTestBegin)==null?void 0:_b.call(reporter,test,ctx)),test.result={start:performance3.now(),state:"run"};try{await callHook(test.suite,"beforeEach",[test,test.suite]),await getFn(test)(),test.result.state="pass"}catch(e){test.result.state="fail",test.result.error=e,process.exitCode=1}try{await callHook(test.suite,"afterEach",[test,test.suite])}catch(e){test.result.state="fail",test.result.error=e,process.exitCode=1}test.result.end=performance3.now(),await((_c=reporter.onTestEnd)==null?void 0:_c.call(reporter,test,ctx))}async function runSuite(suite,ctx){var _a,_b,_c;if(((_a=suite.result)==null?void 0:_a.state)==="fail")return;let{reporter}=ctx;if(await((_b=reporter.onSuiteBegin)==null?void 0:_b.call(reporter,suite,ctx)),suite.result={start:performance3.now(),state:"run"},suite.mode==="skip")suite.result.state="skip";else if(suite.mode==="todo")suite.result.state="todo";else try{await callHook(suite,"beforeAll",[suite]);for(let tasksGroup of partitionSuiteChildren(suite)){let computeMode=tasksGroup[0].computeMode;if(computeMode==="serial")for(let c5 of tasksGroup)await runSuiteChild(c5,ctx);else computeMode==="concurrent"&&await Promise.all(tasksGroup.map(c5=>runSuiteChild(c5,ctx)))}await callHook(suite,"afterAll",[suite])}catch(e){suite.result.state="fail",suite.result.error=e,process.exitCode=1}suite.result.end=performance3.now(),suite.mode==="run"&&(hasTests(suite)?hasFailed(suite)?suite.result.state="fail":suite.result.state="pass":(suite.result.state="fail",suite.result.error||(suite.result.error=new Error(`No tests found in suite ${suite.name}`)),process.exitCode=1)),await((_c=reporter.onSuiteEnd)==null?void 0:_c.call(reporter,suite,ctx))}async function runSuiteChild(c5,ctx){return c5.type==="test"?runTest(c5,ctx):runSuite(c5,ctx)}async function runSuites(suites,ctx){for(let suite of suites)await runSuite(suite,ctx)}async function run(config){var _a,_b,_c;let testFilepaths=await globTestFiles(config);if(!testFilepaths.length){console.error("No test files found"),process.exitCode=1;return}let ctx=await setupRunner(config),{filesMap,snapshotManager,reporter}=ctx;await((_a=reporter.onStart)==null?void 0:_a.call(reporter,config));let newFileMap=await collectTests(testFilepaths);Object.assign(filesMap,newFileMap);let files=Object.values(filesMap);await((_b=reporter.onCollected)==null?void 0:_b.call(reporter,files,ctx)),await runSuites(files,ctx),snapshotManager.saveSnap(),await((_c=reporter.onFinished)==null?void 0:_c.call(reporter,ctx)),config.watch&&await startWatcher(ctx)}if(!process.__vitest__)throw new Error("Vitest can only run in vite-node environment, please use the CLI to start the process");await run(process.__vitest__.config);var timer=setTimeout(()=>{process.exit()},500);timer.unref();
|