使用 Jest、AudioContext 进行测试和模拟

tks*_*kss 5 javascript testing unit-testing typescript jestjs

我在尝试对使用 AudioContext 的类进行一些测试时遇到了很多麻烦。我相信我的很多挫败感源于对模拟函数以及可能的测试执行方式没有很好的理解。

我正在尝试测试一个采用 AudioContext 的类,但是在运行测试时我不断收到此错误:

使用 TypeScript 文件时: TypeError: (window.AudioContext || window.webkitAudioContext) is not a constructor
此错误发生在 app.ts 文件中。当我运行测试时,它是否必须解决或执行它的所有依赖项?

使用 JavaScript 文件时,测试文件中会出现此错误:ReferenceError: AudioContext is not defined

现在,我假设我必须制作一个模拟 AudioContext。我什至如何了解 AudioContext 上的所有方法以开始手动模拟它?

这是我的工作表的简化版本。我将提供两者的 TS 和 JS 版本:

打字稿文件版本:

// 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;      
    }
 }
Run Code Online (Sandbox Code Playgroud)

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;
Run Code Online (Sandbox Code Playgroud)

以粗体显示我之前提到的错误的测试文件:

// 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);
})
Run Code Online (Sandbox Code Playgroud)

更新: 我现在有适用于普通 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 {}
});
Run Code Online (Sandbox Code Playgroud)

由于我的项目是用 TypeScript 编写的,我尝试将模拟添加到我的项目中,但我仍然收到来自上面的错误“TypeError: (window.AudioContext || window.webkitAudioContext) is not a constructor”。

谢谢 :)。

Ben*_*ith 1

您可以通过将窗口指定为“any”类型来解决此问题,即

const audioContext: AudioContext = 
 new (AudioContext || (window as any).webkitAudioContext)();
Run Code Online (Sandbox Code Playgroud)

正如这里所描述的。

请注意,我认为您不需要通过代码中的窗口访问 AudioContext,因为这应该可用。