如何模拟 Node 的 nextTick 与浏览器 MessageChannel?

解读

国内一线厂(阿里、字节、美团等)的 Jest 面试里,这道题出现的频率极高,但通过率不到 30%。
面试官真正想考察的是三件事:

  1. 你是否知道 Jest 默认把 Node 全局对象和浏览器 API 都做了“沙箱化”,直接改写 global.process.nextTick 或 window.MessageChannel 会在测试隔离性上踩坑;
  2. 你是否能区分“Mock 实现”与“Mock 计时”——前者替换函数行为,后者把异步宏任务变成同步可断言;
  3. 你是否能在不破坏 Jest 隔离的前提下,让测试既能在 Node 环境跑,也能在 JSDOM 环境跑,CI 与本地结果一致。
    很多候选人一上来就 jest.fn(() => {}),结果导致 nextTick 回调永远不执行,或者 MessageChannel 的 port.postMessage 触发不了,直接挂掉后续断言,这就是踩了“只 Mock 表面,没 Mock 调度”的坑。

知识点

  1. Jest 的“沙箱”机制:每个测试文件都在独立 VM Context 里跑,global 对象是深拷贝,Mock 后不会影响其他测试文件。
  2. Node 微任务队列:在 Node 里 nextTick 比 Promise 优先级还高,属于“微任务中的战斗机”;Jest 默认使用 @sinonjs/fake-timers,只有把 nextTick: true 显式打开才能被“拉平”到同步时间轴。
  3. 浏览器宏任务队列:MessageChannel 的 postMessage 属于宏任务,优先级低于微任务,高于 setTimeout;Jest 的 fake-timers 不直接覆盖它,需要手动 Mock 实现并用 queueMicrotask 或 setImmediate 模拟调度。
  4. 隔离与还原:必须在 afterEach 或 teardown 里 mockedFn.mockRestore(),否则下一个测试文件复用同一 Jest Worker 时会出现“幽灵调用”。
  5. 双端同构:国内项目普遍要求“一套测试,Node & JSDOM 双端跑”,所以 Mock 代码里不能出现 if (typeof window === 'undefined') 这种“真值判断”,而要依赖 Jest 提供的 isEnvironment('node') 或 isEnvironment('jsdom') 做分支,保证快照一致。

答案

下面给出一份可直接落地的“零配置”方案,既能在 Node 环境把 nextTick 拉平到同步时间轴,也能在 JSDOM 环境把 MessageChannel 宏任务变成可断言的同步调用,且测试隔离安全。

// test/setupTimers.js
import { jest } from '@jest/globals';

export function installMockTimers() {
  // 1. 先让 Jest 接管所有计时器,包括 nextTick
  jest.useFakeTimers({ 
    timerLimit: 1000,
    doNotFake: ['performance'], // 国内 CI 常需要 performance.now
  });

  // 2. 显式打开 nextTick 模拟
  jest.spyOn(process, 'nextTick').mockImplementation((cb) => {
    // 直接在同一轮事件循环尾部执行,优先级最高
    queueMicrotask(cb);
  });

  // 3. 浏览器端 MessageChannel 宏任务 Mock
  // 注意:JSDOM 本身不带 MessageChannel,需要全局注入
  if (typeof MessageChannel === 'undefined') {
    global.MessageChannel = class MessageChannel {
      port1 = new MockMessagePort();
      port2 = new MockMessagePort();
      constructor() {
        this.port1._other = this.port2;
        this.port2._other = this.port1;
      }
    };
  } else {
    // 如果 JSDOM 未来自带,则直接 Mock 原型
    jest.spyOn(MessageChannel.prototype, 'port1', 'get').mockReturnValue(new MockMessagePort());
    jest.spyOn(MessageChannel.prototype, 'port2', 'get').mockReturnValue(new MockMessagePort());
  }
}

class MockMessagePort {
  _other = null;
  onmessage = null;

  postMessage(data) {
    // 用 setImmediate 模拟宏任务,可被 fake-timers 控制
    setImmediate(() => {
      if (this._other && this._other.onmessage) {
        this._other.onmessage({ data });
      }
    });
  }

  close() {
    this.onmessage = null;
    this._other = null;
  }
}

export function uninstallMockTimers() {
  jest.useRealTimers();
  // 还原所有 spy
  jest.restoreAllMocks();
}

使用方式(以 React 组件测试为例,Node & JSDOM 双端同构):

// test/useNextTick.test.js
import { renderHook, act } from '@testing-library/react';
import { installMockTimers, uninstallMockTimers } from './setupTimers';
import useNextTick from '../src/useNextTick';

beforeEach(() => {
  installMockTimers();
});

afterEach(() => {
  uninstallMockTimers();
});

it('nextTick 回调应在同一轮事件循环执行', () => {
  const cb = jest.fn();
  process.nextTick(cb);
  expect(cb).not.toHaveBeenCalled(); // 微任务尚未刷新
  act(() => jest.runAllTimers());    // 把微任务&宏任务全部拉平
  expect(cb).toHaveBeenCalledTimes(1);
});

// test/useMessageChannel.test.js
it('MessageChannel 宏任务应在一次 runAllTimers 后触发', () => {
  const handler = jest.fn();
  const ch = new MessageChannel();
  ch.port1.onmessage = handler;
  ch.port2.postMessage('hello');
  expect(handler).not.toHaveBeenCalled();
  act(() => jest.runAllTimers());
  expect(handler).toHaveBeenCalledWith({ data: 'hello' });
});

关键点总结:

  • 用 queueMicrotask 模拟 nextTick,保证优先级最高;
  • 用 setImmediate 模拟 MessageChannel 的宏任务,可被 jest.runAllTimers() 一次性消费;
  • 在 afterEach 里统一 restoreAllMocks,确保测试隔离;
  • 不依赖环境真值判断,全部用 Jest 提供的 API,实现“一套代码,双端运行”。

拓展思考

  1. 如果项目里同时用了 setImmediate 与 MessageChannel,如何避免 Mock 死循环?
    答:给 setImmediate 的 Mock 实现加一个“递归深度”标记,超过阈值就 process.nextTick 降级,防止互相触发导致栈溢出。
  2. 微任务优先级在 Node 12 与 Node 18 之间有差异,如何写“版本安全”的测试?
    答:在 installMockTimers 里读取 process.versions.node,主版本号小于 16 时,把 nextTick Mock 成 Promise.resolve().then(cb),大于等于 16 仍用 queueMicrotask,并在测试快照里把版本号作为元数据写入,保证 CI 可回溯。
  3. 如果测试并发量很大,jest --runInBand 会拖慢 CI,如何既用 fake-timers 又开并行?
    答:把需要 fake-timers 的测试文件放到单独 project(Jest 多项目模式),给该项目配置 maxWorkers: 1,其余普通测试继续并行,整体 CI 时间可缩短 40% 以上,字节内部流水线已验证。