Storybook 插件手动 Mock
Storybook 手动 Mock 插件可用于模拟你的导入,就像Jest 中的手动 Mock一样
入门
通过添加 storybook-addon-manual-mocks
依赖项来安装此插件
yarn add -D storybook-addon-manual-mocks
# or
npm install --save-dev storybook-addon-manual-mocks
在 .storybook/main.js
中
适用于 Vite 和 Webpack 的通用配置
module.exports = {
addons: [
{
name: "storybook-addon-manual-mocks",
options: {
mocksFolder: "__mocks__",
}
}
],
};
特定的 vite
配置
module.exports = {
addons: [
{
name: "storybook-addon-manual-mocks/vite",
options: {
mocksFolder: "__mocks__",
}
}
],
};
特定的 webpack
配置
module.exports = {
addons: [
{
name: "storybook-addon-manual-mocks/webpack",
options: {
mocksFolder: "__mocks__",
}
}
],
};
可用的 选项
名称 | 类型 | 默认值 | 描述 |
---|---|---|---|
mocksFolder |
字符串 |
"__mocks__" |
自定义 Mock 文件夹 |
如何使用
你可以将服务器查询从组件提取到 hooks 并模拟这些文件
MyComponent
├── __mocks__
│ └── MyComponent.hooks.js
├── MyComponent.component.js
├── MyComponent.stories.js
├── MyComponent.hooks.js
└── index.js
当你将在 MyComponent.component.js
中导入 MyComponent.hooks
时,将使用 __mocks__
目录中的文件代替
import { useSomeData } from 'MyComponent.hooks';
// it will import mock under the hood '__mocks__/MyComponent.hooks';
重要
此插件仅适用于相对导入(例如 ./
或 ../
)
// ✅ this CAN be mocked
import { useSomeData } from './MyComponent.hooks';
// ✅ this CAN be mocked
import { useSomeData } from '../MyComppnent/MyComponent.hooks';
// ⛔️ this CAN'T be mocked
import { useSomeData } from '@monorepo/components/MyComponent/MyComponent.hooks';
// ✅ this CAN be mocked
// Because inside the package, MyComponent.hooks was imported relatively
// `./MyComponent.hooks` by `MyComponent/index.js`, so it will be mocked correctly
import { useSomeData } from '@monorepo/components';