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

如何使用Jest为startTimer函数编写测试用例?

首先得先修正原代码里的几个语法错误,不然根本跑不起来:

  • 变量名session Timeout有空格,改成sessionTimeout
  • Self要小写为self(Web Worker环境里的全局对象是小写self)
  • postMessage传入的对象后面多了个分号,调整为正确的括号闭合

修正后的代码:

function startTimer(event) {
  var sessionTimeout = setTimeout(function () {
    self.postMessage({
      Message: 'show dialog'
    });
  }, event.duration);
}

接下来用Jest写测试用例,步骤如下:

1. 配置测试环境

Jest自带定时器模拟功能,不用额外依赖。在测试文件开头先启用假定时器:

jest.useFakeTimers();

2. 模拟全局的self.postMessage

测试环境没有Web Worker的self对象,手动模拟这个方法:

global.self = { postMessage: jest.fn() };

3. 编写完整测试用例

测试核心是验证两个点:定时器是否按指定时长设置,触发后是否正确调用postMessage并传递参数。

假设你的定时器函数放在timer.js里,测试文件命名为timer.test.js,代码如下:

const { startTimer } = require('./timer');

describe('startTimer 函数测试', () => {
  // 每次测试前重置模拟函数和定时器,避免用例间干扰
  beforeEach(() => {
    jest.clearAllMocks();
    jest.clearAllTimers();
    global.self = { postMessage: jest.fn() };
  });

  test('指定时长后触发postMessage,参数正确', () => {
    const testDuration = 2000; // 测试用的2秒时长
    startTimer({ duration: testDuration });

    // 验证定时器是否被正确调用
    expect(setTimeout).toHaveBeenCalledTimes(1);
    expect(setTimeout).toHaveBeenLastCalledWith(expect.any(Function), testDuration);

    // 快进时间,直接触发定时器
    jest.runAllTimers();

    // 验证postMessage的调用情况
    expect(global.self.postMessage).toHaveBeenCalledTimes(1);
    expect(global.self.postMessage).toHaveBeenCalledWith({ Message: 'show dialog' });
  });
});

额外说明

  • 要确保startTimer函数正确导出,比如在timer.js末尾加module.exports = { startTimer };
  • 如果后续要测试定时器清除逻辑,可以用jest.runOnlyPendingTimers()或者验证clearTimeout的调用

内容的提问来源于stack exchange,提问作者Tamanna Thakur

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 07:15:49