⚠️ 此函式庫適用於 Vue 3 專案。如果您使用 Storybook 與 Vue 2,請改為查看 @storybook/testing-vue!
為何使用此分支?
您可以在測試執行器中呼叫 Story 的 play
方法。如果您已經在使用 Storybook 互動外掛程式,這會很有用。
安裝
此函式庫應安裝為您專案的 devDependencies
之一
透過 npm
npm install --save-dev @storybook/testing-vue3
或透過 yarn
yarn add --dev @storybook/testing-vue3
設定
Storybook CSF
此函式庫要求您使用 Storybook 的 元件 Story 格式 (CSF) 和 提升的 CSF 註解,這是自 Storybook 6 以來建議的撰寫 Story 的方式。
基本上,如果您的 Story 看起來類似這樣,那就沒問題了!
// CSF: default export (meta) + named exports (stories)
export default {
title: "Example/Button",
component: Button
};
export const Primary = () => ({
template: "<my-button primary />"
});
全域設定
這是一個可選步驟。如果您沒有 全域裝飾器,則無需執行此操作。但是,如果您有,這是應用全域裝飾器的必要步驟。
如果您有全域裝飾器/參數/等等,並且希望在測試時將它們應用於您的 Story,您首先需要進行此設定。您可以透過新增或建立 jest 設定檔 來完成此操作
// setupFile.js <-- this will run before the tests in jest.
import { setGlobalConfig } from "@storybook/testing-vue3";
import * as globalStorybookConfig from "./.storybook/preview"; // path of your preview.js file
setGlobalConfig(globalStorybookConfig);
為了讓設定檔被選取,您需要在測試命令中將其作為選項傳遞給 jest
// package.json
{
"test": "jest --setupFiles ./setupFile.js"
}
用法
composeStories
composeStories
將處理您指定的元件中的所有 Story,組合它們中的 args/裝飾器,並傳回包含組合 Story 的物件。
如果您使用組合的 Story (例如 PrimaryButton),元件將會使用 Story 中傳遞的 args 進行渲染。但是,您可以自由地在元件上傳遞任何 props,這些 props 將覆蓋 Story args 中傳遞的預設值。
import { render, screen } from "@testing-library/vue";
import { composeStories } from "@storybook/testing-vue3";
import * as stories from "./Button.stories"; // import all stories from the stories file
// Every component that is returned maps 1:1 with the stories, but they already contain all decorators from story level, meta level and global level.
const { Primary, Secondary } = composeStories(stories);
test("renders primary button with default args", () => {
render(Primary());
const buttonElement = screen.getByText(
/Text coming from args in stories file!/i
);
expect(buttonElement).not.toBeNull();
});
test("renders primary button with overriden props", () => {
render(Secondary({ label: "Hello world" })); // you can override props and they will get merged with values from the Story's args
const buttonElement = screen.getByText(/Hello world/i);
expect(buttonElement).not.toBeNull();
});
composeStory
如果您希望將其應用於單個 Story 而不是所有 Story,則可以使用 composeStory
。您也需要傳遞 meta (預設匯出)。
import { render, screen } from "@testing-library/vue";
import { composeStory } from "@storybook/testing-vue3";
import Meta, { Primary as PrimaryStory } from "./Button.stories";
// Returns a component that already contain all decorators from story level, meta level and global level.
const Primary = composeStory(PrimaryStory, Meta);
test("onclick handler is called", async () => {
const onClickSpy = jest.fn();
render(Primary({ onClick: onClickSpy }));
const buttonElement = screen.getByRole("button");
buttonElement.click();
expect(onClickSpy).toHaveBeenCalled();
});