Tone.js 测试出现 JEST 错误:“ReferenceError: AudioBuffer is not defined”

问题描述

我正在使用 Tone.jsTypescript 中创建一个应用程序,我正在使用 Jest 对其进行测试。

我有一个 Musician 类:

import * as Tone from 'tone';

export class Musician {
    instrument: Tone.Synth;

    constructor() {
        this.instrument = new Tone.Synth().toDestination();
    }
}

这就是我测试它的地方:

import { Musician } from '../src/musician';

test("Musician has an instrument",() => {
    const musician = new Musician();

    expect(musician.instrument).tobedefined();
});

当我运行这个测试时,我得到这个:

terminal output

这是我的tsconfig.json

{
  "compilerOptions": {
    "target": "ES5","module": "commonjs","strict": true,"esModuleInterop": true,"skipLibCheck": true,"forceConsistentCasingInFileNames": true
  }
}

这是我的jest.config.js

module.exports = {
  preset: "ts-jest",testEnvironment: "jsdom",};

解决方法

Jest 作为 node.js 脚本运行,而 AudioBuffer 和 Web Audio 通常在 node.js 环境中不可用。

您基本上必须模拟整个 Web Audio API 来测试您的音频内容。但我会看看tone.js库本身,了解他们如何测试它。

https://github.com/Tonejs/Tone.js/blob/dev/test/helper/SourceTests.ts