You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Storybook中访问Actions标签记录,完成Chromatic交互测试断言?

如何在Chromatic/Storybook交互测试中验证Actions记录(nextRouter.push调用)

要验证点击按钮后nextRouter.push的调用参数,有几种实用的方法,无需依赖Storybook Actions标签页的UI,直接在测试代码里完成断言:

方法1:通过Story Args传递模拟函数(推荐)

这种方式更稳定,符合测试最佳实践:

  1. 在Story定义中,给组件传入模拟的router.push函数:

    • 如果组件直接接收router prop:
    export const MexicanCuisineTest = {
      args: {
        router: {
          push: jest.fn(),
        },
      },
      // 其他Story配置项
    };
    
    • 如果组件用Next.js的useRouter钩子,先mock这个钩子:
    jest.mock('next/router', () => ({
      useRouter: () => ({
        push: jest.fn(),
      }),
    }));
    
  2. 在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标签页看到记录),可以直接读取内部存储:

  1. 确保Story用action函数定义追踪:
import { action } from '@storybook/addon-actions';

export const MexicanCuisineTest = {
  args: {
    router: {
      push: action('nextRouter.push'),
    },
  },
};
  1. 在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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.15 18:43:14