在Mocha&中测试使用Web音频API的库hai [英] Testing A Library That Uses The Web Audio API With Mocha & Chai

查看:81
本文介绍了在Mocha&中测试使用Web音频API的库hai的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建一个使用Web音频api(更具体的说是ToneJS)的库.

I am building a library which uses the web audio api(ToneJS to be more specific).

我尝试使用 jsdom,mocha-jsdom 没有成功.

我收到此错误-

node_modules/tone/build/Tone.js:3869
                this.input = this.output = this._gainNode = this.context.createGain();

这很有意义,并告诉我我需要使用具有上下文的环境.

Which makes sense and tells me that i need to use an environment with a context.

我什至不确定如何为我的项目设置测试.

I'm not even sure how i should setup the tests for my project.

我应该如何为我的项目正确设置测试环境?

How should i setup a test environment correctly for my project?

推荐答案

我建议在单元测试中完全不要使用Tone.js. Tone.js仅在浏览器中有效,因为它需要Web Audio API.相反,您可以使用Tone.js的间谍/模拟/存根(Spy/mock/stub),只需确保您按预期使用Tone.

I would suggest to not use Tone.js at all in your unit tests. Tone.js only works in the browser as it requires the Web Audio API. Instead you could use a spy/mock/stub of Tone.js which just makes sure that you use Tone as intended.

例如,如果您要编写

If you for example want to write a test for the AudioManager you could create a stripped down mock of Tone.js which just provides what you need.

const FakeTone = {
    Players: function () { },
    context: { resume () { } }
};

接下来,我建议重写AudioManager,使其接受Tone作为构造函数参数,而不是将其导入.这将使测试变得容易得多.代替...

Next I would recommend to rewrite the AudioManager in a way that it accepts Tone as a constructor argument instead of importing it. This will make testing a lot easier. Instead of ...

import Tone from 'tone';

export class AudioManager {

    // ...

    generatePlayers () {
        return new Tone.Players()
    }

    // ...

}

...那将是...

... it would then be ...

export class AudioManager {

    constructor (Tone) {
        this.Tone = Tone;
    }

    // ...

    generatePlayers () {
        return new this.Tone.Players();
    }

    // ...

}

...乍一看有点难看,但希望您会在一段时间后习惯它. :-)

... which looks a bit ugly at first, but you hopefully get used to it after a while. :-)

这将允许您使用FakeTone对象测试AudioManager.

This will allow you to test the AudioManager with the FakeTone object.

const audioManager = new AudioManager(FakeTone);

expect(audioManager.generatePlayers()).to.be.an.instanceOf(FakeTone.Players);

您还可以使用 Sinon.JS 之类的东西来编写更高级的测试.

You could also use something like Sinon.JS to write more advanced tests.

这篇关于在Mocha&中测试使用Web音频API的库hai的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆