retainedRoutePages.mount.spec.js 3.38 KB
import fs from "fs";
import path from "path";
import { parse } from "@babel/parser";
import { createLocalVue, shallowMount } from "@vue/test-utils";

globalThis._ = require("lodash");

jest.mock("@/api/request", () => jest.fn(() => Promise.resolve({
	data: {},
	list: [],
	rows: [],
	total: 0,
})));

const localVue = createLocalVue();
localVue.directive("loading", {});

function collectRouteComponents() {
	const moduleRoot = path.resolve(__dirname, "../router/modules");
	const values = new Set();
	for (const file of fs.readdirSync(moduleRoot)) {
		const ast = parse(fs.readFileSync(path.join(moduleRoot, file), "utf8"), { sourceType: "module" });
		const queue = [ast.program];
		while (queue.length) {
			const node = queue.pop();
			if (!node || typeof node !== "object") {
				continue;
			}
			if (node.type === "CallExpression" && node.callee && node.callee.name === "_import") {
				const argument = node.arguments && node.arguments[0];
				if (argument && argument.type === "StringLiteral") {
					values.add(argument.value);
				}
			}
			for (const value of Object.values(node)) {
				if (Array.isArray(value)) {
					queue.push(...value);
				} else if (value && typeof value === "object" && value.type) {
					queue.push(value);
				}
			}
		}
	}
	return [...values].sort();
}

function resolveComponent(componentPath) {
	const direct = path.resolve(__dirname, `${componentPath}.vue`);
	if (fs.existsSync(direct)) {
		return direct;
	}
	const index = path.resolve(__dirname, componentPath, "index.vue");
	if (fs.existsSync(index)) {
		return index;
	}
	throw new Error(`Route component does not exist: ${componentPath}`);
}

function recursiveProxy() {
	const proxy = new Proxy(() => proxy, {
		get(object, property) {
			if (property === Symbol.toPrimitive) {
				return () => "";
			}
			if (property === "length") {
				return 0;
			}
			return proxy;
		},
		apply() {
			return proxy;
		},
	});
	return proxy;
}

function withoutLifecycle(options) {
	return {
		...options,
		beforeCreate: [],
		created: [],
		beforeMount: [],
		mounted: [],
		mixins: (options.mixins || []).map(mixin => withoutLifecycle(mixin.options || mixin)),
		extends: options.extends ? withoutLifecycle(options.extends.options || options.extends) : undefined,
	};
}

describe("retained route page mounts", () => {
	it.each(collectRouteComponents())("%s mounts independently", (componentPath) => {
		const imported = require(resolveComponent(componentPath)).default;
		const options = imported.options || imported;
		const Component = withoutLifecycle(options);
		const proxy = recursiveProxy();
		const wrapper = shallowMount(Component, {
			localVue,
			mocks: {
				$route: { name: "routePageMount", path: "/", query: {}, params: {}, meta: {} },
				$router: { push: jest.fn(), replace: jest.fn(), back: jest.fn() },
				$store: {
					_modulesNamespaceMap: new Proxy({}, {
						get: () => ({ context: { state: proxy, getters: proxy } }),
					}),
					state: proxy,
					getters: proxy,
					dispatch: jest.fn(),
					commit: jest.fn(),
				},
				$message: { success: jest.fn(), warning: jest.fn(), error: jest.fn() },
				$confirm: jest.fn(() => Promise.resolve()),
				$auth: proxy,
				$$: jest.fn(value => value),
			},
			stubs: {
				"d2-container": { template: "<div><slot /></div>" },
				"el-table": { template: "<div><slot /></div>" },
				"el-table-column": true,
			},
		});
		expect(wrapper.exists()).toBe(true);
		wrapper.destroy();
	});
});