vitest 0.0.60 → 0.0.61
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/dist/index.d.ts +8 -2
- package/dist/node/cli.d.ts +1 -1
- package/dist/node/cli.js +2 -2
- package/dist/node/worker.d.ts +1 -1
- package/dist/node/worker.js +2 -2
- package/dist/runtime/entry.d.ts +1 -1
- package/dist/runtime/entry.js +1 -1
- package/dist/{types-c52fcc81.d.ts → types-31dc4f04.d.ts} +6 -0
- package/package.json +1 -1
package/dist/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { T as TestFactory, S as SuiteCollector, a as TestFunction, b as SuiteHooks, U as UserOptions } from './types-
|
|
2
|
-
export { C as CliOptions, e as ComputeMode, F as File, G as GlobalContext, H as HookListener, M as ModuleCache, m as Reporter, R as ResolvedConfig, o as RpcCall, n as RpcMap, q as RpcPayload, p as RpcSend, c as RunMode, i as Suite, S as SuiteCollector, b as SuiteHooks, k as Task, f as TaskBase, g as TaskResult, h as TaskResultPack, d as TaskState, j as Test, l as TestCollector, T as TestFactory, a as TestFunction, U as UserOptions, V as VitestContext, W as WorkerContext } from './types-
|
|
1
|
+
import { T as TestFactory, S as SuiteCollector, a as TestFunction, b as SuiteHooks, U as UserOptions } from './types-31dc4f04';
|
|
2
|
+
export { C as CliOptions, e as ComputeMode, F as File, G as GlobalContext, H as HookListener, M as ModuleCache, m as Reporter, R as ResolvedConfig, o as RpcCall, n as RpcMap, q as RpcPayload, p as RpcSend, c as RunMode, i as Suite, S as SuiteCollector, b as SuiteHooks, k as Task, f as TaskBase, g as TaskResult, h as TaskResultPack, d as TaskState, j as Test, l as TestCollector, T as TestFactory, a as TestFunction, U as UserOptions, V as VitestContext, W as WorkerContext } from './types-31dc4f04';
|
|
3
3
|
export { assert, default as chai, expect, should } from 'chai';
|
|
4
4
|
import sinon from 'sinon';
|
|
5
5
|
export { default as sinon } from 'sinon';
|
|
@@ -141,12 +141,18 @@ declare global {
|
|
|
141
141
|
toBeDefined(): void;
|
|
142
142
|
toBeInstanceOf(c: any): void;
|
|
143
143
|
toBeCalledTimes(n: number): void;
|
|
144
|
+
toHaveLength(l: number): void;
|
|
145
|
+
toBeCloseTo(number: number, numDigits?: number): void;
|
|
144
146
|
toHaveBeenCalledTimes(n: number): void;
|
|
145
147
|
toHaveBeenCalledOnce(): void;
|
|
146
148
|
toHaveBeenCalled(): void;
|
|
147
149
|
toBeCalled(): void;
|
|
148
150
|
toHaveBeenCalledWith(...args: any[]): void;
|
|
149
151
|
toBeCalledWith(...args: any[]): void;
|
|
152
|
+
toHaveBeenNthCalledWith(n: number, ...args: any[]): void;
|
|
153
|
+
nthCalledWith(n: number, ...args: any[]): void;
|
|
154
|
+
toHaveBeenLastCalledWith(...args: any[]): void;
|
|
155
|
+
lastCalledWith(...args: any[]): void;
|
|
150
156
|
toThrow(): void;
|
|
151
157
|
toThrowError(): void;
|
|
152
158
|
toReturn(): void;
|
package/dist/node/cli.d.ts
CHANGED
package/dist/node/cli.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
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.
|
|
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.61";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
2
|
`)}function stringify(obj){return String(obj)}var stackFnCallRE=/at (.*) \((.+):(\d+):(\d+)\)$/,stackBarePathRE=/at ()(.+):(\d+):(\d+)$/;function parseStack(stack){return stack.split(`
|
|
3
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
4
|
`).splice(5);return`
|
|
@@ -17,6 +17,6 @@ ${c3.inverse(" FAIL ")}`)} ${getFullName(test)}`),await printError((_b=test.resu
|
|
|
17
17
|
`)),console.log()),console.log(c3.bold(color(pad("Test Files"))),getStateString(files)),console.log(c3.bold(color(pad("Tests"))),getStateString(tests)),this.watchFilters?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
18
|
${c3.bold(c3.inverse(c3.red(" FAIL ")))}${c3.red(` ${failed.length} tests failed. Watching for file changes...`)}`):console.log(`
|
|
19
19
|
${c3.bold(c3.inverse(c3.green(" PASS ")))}${c3.green(" Watching for file changes...")}`)}async onWatcherRerun(files,trigger){await this.stopListRender(),this.watchFilters=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";import{toArray}from"@antfu/utils";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 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,options.cliFilters&&(resolved.cliFilters=toArray(options.cliFilters));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=((_b=(_a=server.config.test)==null?void 0:_a.deps)==null?void 0:_b.inline)||[],resolved.depsExternal=((_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.cliFilters)==null?void 0:_a.length)&&(testFilepaths=testFilepaths.filter(i=>config.cliFilters.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(cliFilters,argv)=>{process.env.VITEST="true",console.log(c4.magenta(c4.bold(`
|
|
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";import{toArray}from"@antfu/utils";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 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,options.cliFilters&&(resolved.cliFilters=toArray(options.cliFilters));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=((_b=(_a=server.config.test)==null?void 0:_a.deps)==null?void 0:_b.inline)||[],resolved.depsExternal=((_d=(_c=server.config.test)==null?void 0:_c.deps)==null?void 0:_d.external)||[],resolved.interpretDefault=resolved.interpretDefault||!0;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.cliFilters)==null?void 0:_a.length)&&(testFilepaths=testFilepaths.filter(i=>config.cliFilters.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(cliFilters,argv)=>{process.env.VITEST="true",console.log(c4.magenta(c4.bold(`
|
|
21
21
|
Vitest is in closed beta exclusively for Sponsors`))),console.log(c4.yellow(`Learn more at https://vitest.dev
|
|
22
22
|
`));let{config,server}=await initViteServer(__spreadProps(__spreadValues({},argv),{cliFilters})),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=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);
|
package/dist/node/worker.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import '../index';
|
|
2
|
-
import { R as ResolvedConfig, o as RpcCall, p as RpcSend, W as WorkerContext } from '../types-
|
|
2
|
+
import { R as ResolvedConfig, o as RpcCall, p as RpcSend, W as WorkerContext } from '../types-31dc4f04';
|
|
3
3
|
import 'chai';
|
|
4
4
|
import 'sinon';
|
|
5
5
|
import 'worker_threads';
|
package/dist/node/worker.js
CHANGED
|
@@ -1,4 +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{
|
|
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{slash}from"@antfu/utils";var defaultInline=["vitest/dist","vitest/src","@vue","@vueuse","vue-demi","vue",/virtual:/,/\.ts$/,/\/esm\/.*\.js$/,/\.(es|esm|esm-browser|esm-bundler|es6).js$/],depsExternal=[/\.cjs.js$/],isWindows=process.platform==="win32",stubRequests={"/@vite/client":{injectQuery:id=>id,createHotContext(){return{accept:()=>{},prune:()=>{}}},updateStyle(){}}};async function interpretedImport(path,interpretDefault){let mod=await import(path);if(interpretDefault&&"__esModule"in mod&&"default"in mod){let defaultExport=mod.default;return"default"in defaultExport||Object.defineProperty(defaultExport,"default",{enumerable:!0,configurable:!0,get(){return defaultExport}}),defaultExport}return mod}async function executeInViteNode(options){let{moduleCache:moduleCache2,root,files,fetch}=options,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
2
|
Stack:
|
|
3
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
|
|
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 cachedRequest(rawId,callstack){var _a,_b;let id=normalizeId(rawId);if(externaled.has(id))return interpretedImport(id,options.interpretDefault);let fsPath=toFilePath(id,root),importPath=patchWindowsImportPath(fsPath);if(externaled.has(importPath)||await shouldExternalize(importPath,options))return externaled.add(importPath),interpretedImport(importPath,options.interpretDefault);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}async function shouldExternalize(id,config){return matchExternalizePattern(id,config.inline)?!1:matchExternalizePattern(id,config.external)||matchExternalizePattern(id,depsExternal)?!0:matchExternalizePattern(id,defaultInline)?!1:id.includes("/node_modules/")}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 matchExternalizePattern(id,patterns){for(let ex of patterns)if(typeof ex=="string"){if(id.includes(`/node_modules/${ex}/`))return!0}else if(ex.test(id))return!0;return!1}function patchWindowsImportPath(path){return path.match(/^\w:\//)?`/${path}`:path}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,interpretDefault:config.interpretDefault,moduleCache}))[0].run,_run}async function run(ctx){process.stdout.write("\0");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};
|
package/dist/runtime/entry.d.ts
CHANGED
package/dist/runtime/entry.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{getNames,hasFailed,hasTests,interpretOnlyMode,packSnapshotState,partitionSuiteChildren}from"../chunk-4STHXS4C.js";import{clearContext,context,createSuiteHooks,defaultSuite,getFn,getHooks,setHooks}from"../chunk-SLHZBXI2.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("toBeGreaterThan",function(expected){return this.to.greaterThan(expected)}),def("toBeGreaterThanOrEqual",function(expected){return this.to.greaterThanOrEqual(expected)}),def("toBeLessThan",function(expected){return this.to.lessThan(expected)}),def("toBeLessThanOrEqual",function(expected){return this.to.lessThanOrEqual(expected)}),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(["toThrow","toThrowError"],function(){utils.flag(this,"negate")?this.not.to.throw():this.to.throw()}),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-PPDEK7CI.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)},process.stdout.write("\0")}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
|
+
import{getNames,hasFailed,hasTests,interpretOnlyMode,packSnapshotState,partitionSuiteChildren}from"../chunk-4STHXS4C.js";import{clearContext,context,createSuiteHooks,defaultSuite,getFn,getHooks,setHooks}from"../chunk-SLHZBXI2.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("toBeGreaterThan",function(expected){return this.to.greaterThan(expected)}),def("toBeGreaterThanOrEqual",function(expected){return this.to.greaterThanOrEqual(expected)}),def("toBeLessThan",function(expected){return this.to.lessThan(expected)}),def("toBeLessThanOrEqual",function(expected){return this.to.lessThanOrEqual(expected)}),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("toHaveLength",function(length){return this.have.length(length)}),def("toBeCloseTo",function(number,numDigits=2){return utils.expectTypes(this,["number"]),this.closeTo(number,numDigits)});function isSpy(putativeSpy){return typeof putativeSpy=="function"&&typeof putativeSpy.getCall=="function"&&typeof putativeSpy.calledWithExactly=="function"}function isCall(putativeCall){return putativeCall&&isSpy(putativeCall.proxy)}let assertIsMock=assertion=>{if(!isSpy(assertion._obj)&&!isCall(assertion._obj))throw new TypeError(`${utils.inspect(assertion._obj)} is not a spy or a call to a spy!`)};def(["toHaveBeenCalledTimes","toBeCalledTimes"],function(number){return assertIsMock(this),this.callCount(number)}),def("toHaveBeenCalledOnce",function(){return assertIsMock(this),this.callCount(1)}),def(["toHaveBeenCalled","toBeCalled"],function(){return assertIsMock(this),this.called}),def(["toHaveBeenCalledWith","toBeCalledWith"],function(...args){return assertIsMock(this),this.calledWith(...args)});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(["toHaveBeenNthCalledWith","nthCalledWith"],function(times,...args){assertIsMock(this);let nthCall=utils.flag(this,"object").getCall(times-1);this.assert(nthCall.calledWith(...args),`expected ${ordinalOf(times)} spy call to have been called with #{exp}`,`expected ${ordinalOf(times)} spy call not to have been called with #{exp}`,args,nthCall.args)}),def(["toHaveBeenLastCalledWith","lastCalledWith"],function(...args){assertIsMock(this);let spy=utils.flag(this,"object"),lastCall=spy.getCall(spy.returnValues.length-1);this.assert(lastCall.calledWith(...args),"expected last spy call to have been called with #{exp}","expected last spy call not to have been called with #{exp}",args,lastCall.args)}),def(["toThrow","toThrowError"],function(){utils.flag(this,"negate")?this.not.to.throw():this.to.throw()}),def(["toHaveReturned","toReturn"],function(){assertIsMock(this);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){assertIsMock(this);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 assertIsMock(this),this.returned(value)}),def(["toHaveLastReturnedWith","lastReturnedWith"],function(value){assertIsMock(this);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)}),def(["toHaveNthReturnedWith","nthReturnedWith"],function(nthCall,value){assertIsMock(this);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-PPDEK7CI.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)},process.stdout.write("\0")}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};
|
|
@@ -116,6 +116,12 @@ interface UserOptions {
|
|
|
116
116
|
* Custom reporter for output
|
|
117
117
|
*/
|
|
118
118
|
reporter?: Reporter;
|
|
119
|
+
/**
|
|
120
|
+
* Interpret CJS module's default as named exports
|
|
121
|
+
*
|
|
122
|
+
* @default true
|
|
123
|
+
*/
|
|
124
|
+
interpretDefault?: boolean;
|
|
119
125
|
}
|
|
120
126
|
interface CliOptions extends UserOptions {
|
|
121
127
|
/**
|