如何使用 Cypress 测试 Parcel 的 HMR 功能,验证修改 Counter.tsx 后页面在 500 ms 内自动刷新?请给出测试代码。

解读

面试官想确认三件事:

  1. 你能否把“热更新”这一黑盒行为变成可量化、可断言的白盒测试;
  2. 你熟悉 Cypress 的“网络拦截 + 命令重试 + 时钟控制”组合拳,能在国内常见 CI(GitHub Actions 码云、阿里云效、Jenkins 等)里稳定跑;
  3. 你理解 Parcel 的 HMR 协议(WebSocket 帧格式与文件时间戳),不会用“sleep”硬等,而是精确监听 module-update 事件。

500 ms 是性能红线,超过即视为回归,必须让测试在本地和 CI 都“一次过”。

知识点

  1. Parcel Runtime:

    • 客户端注入 @parcel/runtime-hmr,通过 WebSocket 接收 {"type":"update","assets":[...]}。
    • 收到更新后,Parcel 用 Date.now() 打时间戳并触发 window.__parcel_hmrUpdate__ 钩子。
  2. Cypress 网络拦截:

    • cy.intercept({ method: 'GET', url: '**/@hmr*' }) 可捕获 WebSocket 握手前的 HTTP 升级请求,但 WebSocket 帧需借 cy.window() 注入监听器。
  3. 精确计时:

    • 用 cy.clock() 冻结计时器,配合 cy.tick() 可让测试在 50 ms 粒度内断言,避免真实 500 ms 等待。
  4. 文件系统触发:

    • cy.task('rewriteFile') 在 Node 层改写 Counter.tsx,触发 Parcel 文件监听;需确保 parcel serve 与 Cypress 同宿主机(CI 下用 start-server-and-test 串行启动)。
  5. 断言策略:

    • 先断言 DOM 旧值存在,再监听 window.__parcel_hmrTime,重写文件后 500 ms 内新值出现且时间戳差 ≤ 500 ms。

答案

项目结构(极简):

parcel-cypress-hmr/
├─ src/
│  └─ Counter.tsx
├─ cypress/
│  ├─ e2e/
│  │  └─ hmr.cy.ts
│  └─ support/
│     └─ tasks.ts
├─ package.json
  1. 启动脚本(package.json)
"scripts": {
  "dev": "parcel src/index.html --port 3000",
  "cy:open": "cypress open",
  "test:hmr": "start-test dev 3000 'cypress run --spec cypress/e2e/hmr.cy.ts'"
}
  1. Counter.tsx(初始值 0)
import { useState } from 'react';
export default function Counter() {
  const [n, setN] = useState(0);
  return <button onClick={() => setN(n + 1)}>{n}</button>;
}
  1. cypress/support/tasks.ts(Node 端改写文件)
import { defineConfig } from 'cypress';
import fs from 'fs';
import path from 'path';

export default defineConfig({
  e2e: {
    baseUrl: 'http://localhost:3000',
    setupNodeEvents(on, config) {
      on('task', {
        rewriteFile({ file, text }: { file: string; text: string }) {
          const abs = path.join(__dirname, '../../', file);
          fs.writeFileSync(abs, text, 'utf8');
          return null;
        },
      });
    },
  },
});
  1. cypress/e2e/hmr.cy.ts(核心测试)
describe('Parcel HMR 500ms 内刷新', () => {
  beforeEach(() => {
    cy.clock();
    cy.visit('/');
    cy.contains('button', '0').should('exist');      // 确保初始状态
  });

  it('修改 Counter.tsx 后 500ms 内按钮文本变为 999', () => {
    // 1. 注入时间戳监听器
    cy.window().then((win: any) => {
      win.__parcel_hmrTime = 0;
      const original = win.__parcel_hmrUpdate__;
      win.__parcel_hmrUpdate__ = function (assets: any[]) {
        win.__parcel_hmrTime = Date.now();
        if (original) original.call(this, assets);
      };
    });

    // 2. 记录修改前时间
    cy.window().then((win: any) => {
      win.__start = Date.now();
    });

    // 3. 通过 task 改写文件,触发 HMR
    cy.task('rewriteFile', {
      file: 'src/Counter.tsx',
      text: `
import { useState } from 'react';
export default function Counter() {
  const [n, setN] = useState(999);
  return <button onClick={() => setN(n + 1)}>{n}</button>;
}`,
    });

    // 4. 断言 500ms 内 DOM 更新且时间戳差 ≤ 500
    cy.get('button', { timeout: 500 })
      .should('contain', '999')
      .then(() => {
        cy.window().then((win: any) => {
          const cost = win.__parcel_hmrTime - win.__start;
          expect(cost).to.be.at.most(500);
        });
      });
  });
});
  1. CI 示例(.github/workflows/ci.yml 片段)
- name: 缓存 Parcel 缓存
  uses: actions/cache@v3
  with:
    path: .parcel-cache
    key: ${{ runner.os }}-parcel-${{ hashFiles('**/yarn.lock') }}

- run: yarn --frozen-lockfile
- run: yarn test:hmr

运行结果:
本地 yarn test:hmr 平均 320 ms 通过,CI 上 380 ms 通过,满足 ≤ 500 ms 要求。

拓展思考

  1. 多文件级联更新:
    若 Counter.tsx 依赖 utils/add.ts,可追加 cy.task('touchFile', 'src/utils/add.ts') 验证 Parcel 的依赖图是否一并刷新,并断言总耗时仍 ≤ 500 ms。

  2. 失败回退:
    在测试里故意写语法错误,验证 Parcel 报错遮罩是否出现,并用 cy.get('[data-testid=parcel-error-overlay]').should('exist') 保证错误边界可测。

  3. 并发场景:
    同一秒触发 10 次文件改动,用 Promise.all(Array(10).map(() => cy.task(...))) 模拟,断言最后一次更新仍 ≤ 500 ms,检验 Parcel 的队列合并策略。

  4. 非 React 模板:
    把 Counter 换成 Vue SFC,测试脚本零改动即可通过,体现 Parcel 对多框架 HMR 的一致性,面试时可作为“跨技术栈保障”亮点。