我在我的项目中的函数中有以下代码;
....
if (state.context == null) {
return {
...state,
context: new AudioContext()
}
}
....
我在试着在Jest测试这种行为。然而,Jest使用不支持AudioContext()
的jsdom
在我使用的其他测试中;
.....
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
我还发现了这个图书馆,它似乎可以工作,只是它要求您在代码中使用这个函数的模拟版本,而不是像我对random()
那样重载它。
我会将jsdom替换为我的测试环境,但是,我还没有找到一个支持AudioContext()
的环境。
有没有不改变源代码的解决方案?传递到在运行时调用AudioContext()
为模拟或函数AudioContext
的函数?
发布于 2021-12-03 01:29:43
我是问题中提到的图书馆的作者。我认为以下几点应该有效。
import { AudioContext } from 'standardized-audio-context-mock';
global.AudioContext = AudioContext;
然而,我自己并不是一个Jest用户。如果它不起作用,请让我知道,如果您遇到任何错误,请随时通知公开问题。
https://stackoverflow.com/questions/70203182
复制相似问题