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

求助:在Jest中使用AudioContext提示‘AudioContext is not defined’

解决Jest中AudioContext未定义的问题

方案1:单个测试文件内局部模拟

在用到该服务的测试文件顶部,直接全局模拟AudioContext,按需实现服务中用到的方法:

// 测试文件开头
global.AudioContext = jest.fn().mockImplementation(() => ({
  // 模拟服务实际调用的AudioContext方法,示例:
  createBufferSource: jest.fn().mockReturnValue({
    connect: jest.fn(),
    start: jest.fn(),
    stop: jest.fn()
  }),
  createGain: jest.fn().mockReturnValue({
    connect: jest.fn(),
    gain: { value: 1 }
  })
}));

方案2:全局配置,所有测试生效

如果多个测试文件都需要用到,可在Jest全局配置中添加模拟:

  1. 修改jest.config.js,指定初始化文件:
module.exports = {
  setupFilesAfterEnv: ['./jest.setup.js']
};
  1. 在项目根目录创建jest.setup.js,写入全局模拟代码:
global.AudioContext = jest.fn().mockImplementation(() => ({
  // 按需模拟所需方法,示例:
  createBufferSource: jest.fn().mockReturnValue({
    connect: jest.fn(),
    start: jest.fn()
  })
}));

注意事项

  • 模拟的方法需和服务中实际调用的保持一致,否则会出现“方法未定义”的新报错
  • 可通过jest.spyOn或mock的mock.calls属性,验证AudioContext及其方法的调用情况

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 10:32:13