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