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

使用TypeScript与Jest编写单元测试时遭遇Unexpected reserved word 'yield'错误

解决Jest + TypeScript测试中"Unexpected reserved word 'yield'"错误

问题根源

你在测试回调里使用了await,但没有将函数标记为async。Jest解析时会把非async函数里的await误识别为生成器语法里的yield,从而抛出语法错误。

修复步骤

  • 修正测试函数的异步标记:把测试回调改为async函数,这是最直接的解决方法:
it("should do things right", async () => {
    const payload = { ... };
    await manager.init(payload);
});
  • 验证Jest的TypeScript配置:
    1. 确保已安装必要依赖:@types/jest、ts-jest、typescript
    2. 在jest.config.js中配置ts-jest预设:
module.exports = {
  preset: 'ts-jest',
  testEnvironment: 'jsdom', // 前端项目用jsdom,后端服务用node
};
  • 检查TypeScript编译目标:确保tsconfig.json的target版本支持async/await(ES2017及以上即可):
{
  "compilerOptions": {
    "target": "ES2017",
    // 其他项目配置...
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 04:20:27