如何在Storybook中访问Actions标签记录,完成Chromatic交互测试断言?
如何在Chromatic/Storybook交互测试中验证Actions记录(nextRouter.push调用)
要验证点击按钮后nextRouter.push的调用参数,有几种实用的方法,无需依赖Storybook Actions标签页的UI,直接在测试代码里完成断言:
方法1:通过Story Args传递模拟函数(推荐)
这种方式更稳定,符合测试最佳实践:
在Story定义中,给组件传入模拟的
router.push函数:- 如果组件直接接收
routerprop:
export const MexicanCuisineTest = { args: { router: { push: jest.fn(), }, }, // 其他Story配置项 };- 如果组件用Next.js的
useRouter钩子,先mock这个钩子:
jest.mock('next/router', () => ({ useRouter: () => ({ push: jest.fn(), }), }));- 如果组件直接接收
在play函数中直接访问模拟函数并断言:
import { useRouter } from 'next/router'; play: async ({ canvasElement, args }) => { const canvas = within(canvasElement); await userEvent.click(await canvas.findByRole('button', { name: 'Mexican' })); // 对应组件接收router prop的情况 expect(args.router.push).toHaveBeenCalledWith("?cuisineOption=MEXICAN"); // 对应组件用useRouter钩子的情况 expect(useRouter().push).toHaveBeenCalledWith("?cuisineOption=MEXICAN"); },
方法2:直接读取Storybook Action Store的记录
如果组件已经通过Storybook Actions addon追踪了nextRouter.push(能在Actions标签页看到记录),可以直接读取内部存储:
- 确保Story用
action函数定义追踪:
import { action } from '@storybook/addon-actions'; export const MexicanCuisineTest = { args: { router: { push: action('nextRouter.push'), }, }, };
- 在play函数中读取记录并断言:
play: async ({ canvasElement }) => { const canvas = within(canvasElement); await userEvent.click(await canvas.findByRole('button', { name: 'Mexican' })); const actionStore = window.__STORYBOOK_ACTION_STORE__; const pushCalls = actionStore.getActions('nextRouter.push'); // 断言最后一次调用的参数正确 expect(pushCalls.at(-1).args[0]).toBe("?cuisineOption=MEXICAN"); },
注意:window.__STORYBOOK_ACTION_STORE__是Storybook内部API,不同版本可能有变动,优先推荐方法1。
内容的提问来源于stack exchange,提问作者jmargolisvt
相关产品推荐
相关产品推荐

