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

Jest测试async函数报regeneratorRuntime未定义错误求助

问题修复方案

ReferenceError: regeneratorRuntime is not defined 是async/await语法所需的运行时polyfill缺失导致的,和测试用例写法无关,按以下步骤修复:


1. 修复运行时依赖问题

  • 安装相关依赖
    执行命令:
npm install --save-dev @babel/preset-env @babel/plugin-transform-runtime
npm install --save @babel/runtime
  • 配置Babel
    在项目根目录新增/修改.babelrc(或babel.config.json)文件,写入以下配置:
{
  "presets": [
    ["@babel/preset-env", { "targets": { "node": "current" } }]
  ],
  "plugins": ["@babel/plugin-transform-runtime"]
}

如果是TypeScript项目,可直接在tsconfig.json中将compilerOptions.target调整为ES2017及以上,无需额外安装Babel依赖;若必须兼容低版本目标,可安装regenerator-runtime包,在测试入口文件顶部添加import 'regenerator-runtime/runtime'即可。


2. 修复测试相关问题

Jest默认的jsdom运行环境没有内置cookieStoreAPI,即使修复了polyfill问题,后续也会出现cookieStore is not defined错误,需要手动Mock该API:
在测试文件顶部添加Mock逻辑:

// 全局mock cookieStore
global.cookieStore = {
  get: jest.fn()
}

你之前写的部分测试用例存在语法错误,例如没有等待异步函数执行完成就直接断言,推荐使用更简洁的async/await写法写测试用例:

describe('checkData 功能测试', () => {
  // 每次测试前清空mock调用记录,避免用例互相干扰
  beforeEach(() => {
    jest.clearAllMocks();
  });

  it('sample cookie有效时返回true', async () => {
    // 模拟返回未过期的cookie
    cookieStore.get.mockResolvedValue({
      name: 'sample',
      expires: Date.now() + 2 * 3600 * 1000
    });
    const res = await checkData();
    expect(res).toBe(true);
    expect(cookieStore.get).toHaveBeenCalledWith('sample');
  });

  // 可根据业务逻辑补充其他场景用例,比如cookie过期、不存在等场景
})

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 06:39:03