@emdash-cms/plugin-test 建置沙盒外掛程式並在 workerd 中執行其測試。測試使用 EmDash 的生產 Cloudflare 沙盒包裝器和 PluginBridge,以及由 @cloudflare/vitest-plugin 提供的本機 D1 和 Worker Loader 繫結。
使用 emdash-plugin init 建立的專案包含此設定。現有外掛程式專案可以將測試主機安裝為開發相依性:
pnpm add -D @emdash-cms/plugin-test vitest
如果專案限制相依性的建置指令碼,請允許 workerd 安裝其平台二進位檔。產生的 pnpm 原則包含此項目:
allowBuilds:
workerd: true
設定 Vitest
將 EmDash 測試外掛程式新增到專案的 Vitest 設定中:
import { emdashPluginTest } from "@emdash-cms/plugin-test/config";
import { defineConfig } from "vitest/config";
export default defineConfig({
plugins: [emdashPluginTest()],
});
emdashPluginTest() 在 Vitest 啟動前執行外掛程式建置。它讀取產生的執行階段和資訊清單,建立一個隔離的 D1 資料庫和 Worker Loader 繫結,並匯出 Cloudflare 部署使用的相同 PluginBridge。當 Vitest 設定位於外掛程式目錄之外時,傳入 { dir: "./packages/gallery" }。
測試路由
在每個測試中建立和銷毀主機。銷毀會停止外掛程式並重設其測試繫結:
import { afterEach, describe, expect, it } from "vitest";
import { createPluginTestHost, type PluginTestHost } from "@emdash-cms/plugin-test";
let host: PluginTestHost | undefined;
afterEach(async () => {
await host?.dispose();
host = undefined;
});
describe("health route", () => {
it("identifies the plugin", async () => {
host = await createPluginTestHost();
await expect(host.invokeRoute("health")).resolves.toEqual({
ok: true,
plugin: "save-log",
});
});
});
invokeRoute() 接受輸入值和選用的請求屬性。預設請求是對外掛程式路由的 POST,帶有空的標頭和請求中繼資料。
測試掛鉤和儲存
使用從 EmDash 接收的事件形式呼叫掛鉤。儲存和 KV 讀取器檢查透過橋接寫入的狀態:
host = await createPluginTestHost();
await host.invokeHook("content:afterSave", {
collection: "posts",
content: { id: "post-1", title: "First post" },
});
const events = await host.storage("events").list();
expect(events).toHaveLength(1);
expect(events[0]?.data).toMatchObject({
collection: "posts",
contentId: "post-1",
});
儲存呼叫仍然強制執行 emdash-plugin.jsonc 中宣告的集合。內容、媒體、使用者、電子郵件和網路呼叫仍然強制執行外掛程式宣告的功能和允許的主機。
填入內容
在呼叫讀取網站內容的路由或掛鉤之前,建立集合並填入條目:
host = await createPluginTestHost();
await host.createCollection({
slug: "posts",
label: "Posts",
fields: [{ slug: "title", label: "Title", type: "string" }],
});
await host.seedContent("posts", [{ title: "First" }, { title: "Second" }]);
await expect(host.invokeRoute("post-count")).resolves.toEqual({ count: 2 });
集合和條目使用 D1 上的真實 EmDash 結構描述登錄和內容儲存庫。
測試邊界
主機涵蓋建置的外掛程式、隔離邊界、遠端程序呼叫序列化、D1 行為、功能檢查、掛鉤、路由、KV 和宣告的儲存。它不會算繪 EmDash 管理應用程式,也不會重現 Cloudflare 部署的 CPU、記憶體和子請求限制。使用一次性 EmDash 網站進行瀏覽器旅程,並在 Cloudflare 預覽或預發佈部署上驗證對限制敏感的行為。
對於 Block Kit 處理常式,呼叫外掛程式的 admin 路由並斷言傳回的區塊文件。使用 Block Playground 或瀏覽器旅程來驗證算繪的版面配置和互動。