【问题标题】:Tone.js test with JEST error: "ReferenceError: AudioBuffer is not defined"带有 JEST 错误的 Tone.js 测试:“ReferenceError:未定义 AudioBuffer”
【发布时间】:2021-11-17 02:45:58
【问题描述】:

我正在使用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();
});

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

这是我的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",
};

【问题讨论】:

    标签: typescript jestjs ts-jest tone.js


    【解决方案1】:

    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

    【讨论】:

      【解决方案2】:

      首先,您应该只导入所需的工具

      // business.layer.js
      import { Synth, PolySynth } from 'tone'
      
      ...
      
      const synth = new PolySynth(Synth).toDestination()
      

      其次,你应该在你的测试文件中模拟使用的操作

      // *.test.js
      jest.mock('tone', () => {
        return {
          PolySynth: jest.fn(),
          Synth: jest.fn().mockImplementation(() => {
            return { toDestination: jest.fn() }
          })
        }
      })
      

      【讨论】:

        猜你喜欢
        • 2021-12-24
        • 2021-08-01
        • 1970-01-01
        • 1970-01-01
        • 2021-06-12
        • 2021-05-09
        • 2019-12-16
        • 2022-11-17
        • 2022-12-31
        相关资源
        最近更新 更多