UNPKG

vitest-auto-mock

Version:

Library for mocking dependencies in Vitest with TypeScript without need to provide a path.

4 lines (3 loc) 1.19 kB
"use strict";const u=require("vite"),p=require("vitest/config"),m="vi",f="mocked";function d(){let e=null;return{name:"vite-plugin-vitest-auto-mock",configResolved:({test:t})=>{const r=(t==null?void 0:t.include)??p.configDefaults.include;e=u.createFilter(r)},transform(t,r){return!e||!e(r)?void 0:{code:g(t,this.parse)}}}}const g=(e,t)=>{const n=t(e).body,o=n.filter(k),i=y(n);if(i.length===0)return e;const c=M(o),l=i.map(c);return h(l).concat(e)},y=e=>{const t=e.filter(o=>o.type==="VariableDeclaration").map(o=>o.declarations[0].init),r=e.filter(C).map(o=>o.expression).filter(a);return[...t,...r].filter(a).filter(I)},I=e=>{const t=e.callee;if(!E(t))return!1;const r=t.object;if(!s(r)||r.name!==m)return!1;const n=t.property;return s(n)?n.name===f:!1},M=e=>t=>A(e,t),A=(e,t)=>{const r=t.arguments[0];return s(r)?b(e,r.name):null},a=e=>!!e&&e.type==="CallExpression",s=e=>e.type==="Identifier",E=e=>e.type==="MemberExpression",C=e=>e.type==="ExpressionStatement",k=e=>e.type==="ImportDeclaration",b=(e,t)=>e.filter(r=>x(r,t)).map(r=>r.source.raw)[0]??null,x=(e,t)=>e.specifiers.some(r=>r.local.name===t),h=e=>` `+e.filter(t=>!!t).map(t=>`vi.mock(${t});`).join(` `);module.exports=d;