UNPKG

vitest-auto-mock

Version:

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

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