Storybook Apollo Client 插件
在你的 Storybook story 中使用 Apollo Client。
版本
- 如果你正在使用 Apollo Client 2.x 和 Storybook 5.x,请使用 1.x 版本
- 如果你正在使用 Apollo Client 2.x 或 3.x 和 Storybook 6.x,请使用 4.x 版本
安装
yarn
yarn add --dev storybook-addon-apollo-client
npm
npm install -D storybook-addon-apollo-client
将插件添加到你的 .storybook/main.js
配置文件中
module.exports = {
...config,
addons: [
...your addons
"storybook-addon-apollo-client",
],
};
将以下内容添加到你的 .storybook/preview.js
中
import { MockedProvider } from '@apollo/client/testing'; // Use for Apollo Version 3+
// import { MockedProvider } from "@apollo/react-testing"; // Use for Apollo Version < 3
export const parameters = {
apolloClient: {
MockedProvider,
// any props you want to pass to MockedProvider on every story
},
};
从旧版本升级
在以前的版本中,我们有一个名为 withApolloClient
的装饰器,现在不再需要它了。如果你从这个 API 升级,你需要进行以下更改
- 删除所有引用已弃用的 withApolloClient 装饰器的代码。
- 遵循安装说明
使用查询编写你的 stories
import DashboardPage, { DashboardPageQuery } from '.';
export default {
title: 'My Story',
};
export const Example = () => <DashboardPage />;
Example.parameters = {
apolloClient: {
// do not put MockedProvider here, you can, but its preferred to do it in preview.js
mocks: [
{
request: {
query: DashboardPageQuery,
},
result: {
data: {
viewer: null,
},
},
},
],
},
};
在 https://apollo.graphql.net.cn/docs/react/development-testing/testing 阅读更多关于 MockedProvider 可用选项的信息
用法
在 Storybook 中,点击“显示插件”并导航到“Apollo Client”选项卡。
示例应用
要查看此插件的实际使用示例,请查看示例应用
https://github.com/lifeiscontent/realworld
加载状态
你可以使用 delay
参数来模拟加载状态。
import DashboardPage, { DashboardPageQuery } from '.';
export default {
title: 'My Story',
};
export const Example = () => <DashboardPage />;
Example.parameters = {
apolloClient: {
mocks: [
{
// Use `delay` parameter to increase loading time
delay: 1e21,
request: {
query: DashboardPageQuery,
},
result: {
data: {},
},
},
],
},
};
错误状态
你可以使用 error
参数来创建错误状态。
import DashboardPage, { DashboardPageQuery } from '.';
export default {
title: 'My Story',
};
export const Example = () => <DashboardPage />;
Example.parameters = {
apolloClient: {
mocks: [
{
request: {
query: DashboardPageQuery,
},
error: new Error('This is a mock network error'),
},
],
},
};