【发布时间】:2022-01-09 03:57:16
【问题描述】:
我的项目中的函数中有以下代码;
....
if (state.context == null) {
return {
...state,
context: new AudioContext()
}
}
....
我正在尝试在 Jest 中测试这种行为。但是,Jest 使用的 jsdom 不支持 AudioContext()
在我使用的其他测试中;
.....
jest.spyOn(global.Math, 'random').mockReturnValue(0.3);
....
jest.spyOn(global.Math, 'random').mockRestore();
....
这不起作用。当我打电话给spyOn(global /* or window */, 'AudioContext') 时,我收到错误Cannot spy the AudioContext property because it is not a function; undefined given instead
我还发现了这个library,它似乎可以工作,只是它要求您在代码中使用函数的模拟版本,而不是像我对random() 所做的那样重载它。
我会替换 jsdom 作为我的测试环境,但是我一直找不到支持AudioContext() 的环境。
是否有不更改源代码的解决方案?在运行时向调用AudioContext() 的函数传递一个模拟或函数AudioContext?
【问题讨论】:
标签: unit-testing jestjs mocking audiocontext