我在尝试对使用 AudioContext 的类进行一些测试时遇到了很多麻烦。我相信我的很多挫败感源于对模拟函数以及可能如何执行测试没有很好的理解。
我正在尝试测试一个采用 AudioContext 的类,但是在运行测试时我一直收到此错误:
使用 TypeScript 文件时:
TypeError: (window.AudioContext || window.webkitAudioContext) 不是构造函数
此错误发生在 app.ts 文件中。当我运行测试时,它是否必须解析或执行它的所有依赖项?
当使用 JavaScript 文件时,测试文件中会出现此错误:ReferenceError: AudioContext is not defined
现在,我假设我必须制作一个模拟 AudioContext。我如何了解 AudioContext 上的所有方法以开始手动模拟它?
这是我的工作表的简化版本。我将提供两者的 TS 和 JS 版本:
TypeScript 文件版本:
// app.ts
import Sampler from './Sampler';
const audioContext: AudioContext = new (window.AudioContext || window.webkitAudioContext)();
const sampler: Sampler = new Sampler(audioContext);
// Sampler.ts
export default class Sampler{
private audioContext: AudioContext;
constructor(audioContext: AudioContext){
this.audioContext = audioContext;
}
}
JS 文件版本:
// app.js
const Sampler = require('./Sampler');
const audioContext = new (window.AudioContext || window.webkitAudioContext)();
const sampler = new Sampler(audioContext);
// Sampler.js
class Sampler{
constructor(audioContext){
this.audioContext = audioContext;
}
}
module.exports = Sampler;
出现我之前提到的粗体错误的测试文件:
// sampler.test.ts
import Sampler from './Sampler';
// Uncomment line below if you're using plain JS and not TS
// const Sampler = require('./Sampler');
test('Test test', () => {
const audioContext = new AudioContext();
const s = new Sampler(audioContext);
})
更新: 我现在有适用于普通 JS 文件的代码。我在测试中添加了一个空的 AudioContext 模拟。
// sampler.test.js
const Sampler = require('./Sampler');
require('./__mocks__/app');
test('Testing Mock AudioContext', () => {
const audioContext = new AudioContext();
const s = new Sampler(audioContext);
})
// __mocks__/app.js
window.AudioContext = jest.fn().mockImplementation(() => {
return {}
});
由于我的项目是用 TypeScript 编写的,所以我尝试将 mock 添加到我的项目中,但我仍然收到上面的错误“TypeError: (window.AudioContext || window.webkitAudioContext) is not a constructor”。
谢谢 :).
最佳答案
旧帖子,但我想我会分享我是如何处理 typescript 错误的。为了保持 Typescript 和类型的影响力,我只是将 webkitAudioContext
添加到定义的 Window
类型中。我的代码如下所示:
declare var window: {
webkitAudioContext: typeof AudioContext;
} & Window & typeof globalThis;
const audioContext = new (window.AudioContext || window.webkitAudioContext)();
这实质上告诉 typescript 将 Window & typeof globalThis
与新的 webkitAudioContext
属性合并。
至于 ReferenceError: AudioContext is not defined 错误,这很可能是因为 AudioContext
没有被模拟(就像你说的——这也是我的问题搜索我偶然发现您的帖子的时间)。我知道开 Jest 使用 jsdom 来模拟 dom。 jsdom currently doesn't support AudioContext mocks
关于javascript - 使用 Jest、AudioContext 进行测试和模拟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55616119/