使用 @wordpress/scripts 内置 Jest,如何测试块属性变更?

解读

在国内 WordPress 岗位面试中,块属性变更测试是衡量候选人是否真正掌握 Gutenberg 可重用组件与数据流的关键。面试官想确认三点:

  1. 你是否理解 @wordpress/scripts 已经封装了 Jest + @testing-library 的完整链路,无需自己搭环境;
  2. 你是否会用 render 与 fireEvent 模拟用户输入,而不是直接改 DOM;
  3. 你是否能断言 attributes 对象被正确更新,并验证 save 函数输出同步变化。
    答不到“用 wp.data.dispatch 触发变更后断言序列化结果”这一层,基本会被判为“只写过静态块”。

知识点

  • @wordpress/scripts 的 jest.config.js 已内置 @testing-library/react、@wordpress/jest-console,支持 JSX 转译与 import '@wordpress/block-editor' 的 alias;
  • 块属性变更本质 是调用 setAttributes,而 setAttributes 由 wp.data.dispatch('core/block-editor').updateBlockAttributes 驱动;
  • 测试时必须 mock 块编辑器上下文,提供 registerBlockType 产生的真实 edit 组件与 attributes 状态;
  • 断言方向:① attributes 快照;② save 函数返回的静态 HTML;③ 控制台无弃用警告(国内主机环境老旧,警告=扣分);
  • 性能陷阱:避免 waitFor 无限轮询,使用 findBy* 或 rerender 主动刷新;
  • CI 场景:GitHub Actions 国内镜像源常超时,需在 jest.setup.js 里加 --runInBand 与 npm config set puppeteer_skip_chromium_download=true。

答案

  1. 项目根目录已执行 npm i -D @wordpress/scripts,无需额外安装 jest。
  2. 在 test/index.test.js 中编写用例:
import { registerBlockType } from '@wordpress/blocks';
import { render, fireEvent, screen } from '@testing-library/react';
import '@testing-library/jest-dom';
import json from '../block.json';

// 引入真实源码
import Edit from '../src/edit';
import save from '../src/save';

// 注册块,确保 Hook 正常
beforeAll(() => {
  registerBlockType(json.name, {
    ...json,
    edit: Edit,
    save,
  });
});

test('用户修改文字后属性与序列化结果同步变更', async () => {
  const initialAttributes = { message: '初始值' };
  let currentAtts = initialAttributes;
  const setAttributes = jest.fn((newAtts) => {
    currentAtts = { ...currentAtts, ...newAtts };
  });

  // 第一次渲染
  const { rerender } = render(
    <Edit attributes={currentAtts} setAttributes={setAttributes} />
  );

  const input = screen.getByPlaceholderText('请输入文字');
  fireEvent.change(input, { target: { value: '中国智造' } });

  // 断言 setAttributes 被正确调用
  expect(setAttributes).toHaveBeenCalledWith({ message: '中国智造' });

  // 模拟父组件刷新,传入最新 attributes
  rerender(<Edit attributes={currentAtts} setAttributes={setAttributes} />);
  expect(input.value).toBe('中国智造');

  // 断言 save 函数输出
  const saved = save({ attributes: currentAtts });
  expect(saved).toMatchInlineSnapshot(`<p class="wp-block-demo-message">中国智造</p>`);
});
  1. 运行 npm run test:unit,国内镜像卡顿可加 npm run test:unit -- --runInBand。
  2. 若块内使用 withSelect/withDispatch,需用 wp.data.use 提供 mock store,否则会出现“Cannot read property getSelectedBlock of undefined”错误。

拓展思考

  • 服务端渲染(SSR)场景:国内 SEO 要求极高,需额外测试 save 返回的 HTML 是否满足 百度 MIP 规范,可在 Jest 里用 jest-dom 的 toHaveAttribute('data-mip)', '') 断言。
  • 属性类型为对象数组:如 slides: [{ url, id }],变更时容易触发 “对象引用未变”导致 React 不刷新 的坑,测试用例需 expect.any(Object) 并深拷贝断言。
  • CI/CD 与微信通知:国内公司常用 码云 Gitee + 企业微信机器人,在 jest.config.js 的 reporters 里加 jest-wechat-reporter,失败时自动 @ 开发者,提高响应速度。