gpt4 book ai didi

javascript - 如何在 Jasmine 测试中释放 AudioContext

转载 作者:行者123 更新时间:2023-12-02 15:39:03 27 4
gpt4 key购买 nike

我有一个 Angular 服务来设置 audioContext。 Jasmine 正在为每个测试创建一个新服务,因此在 6 次测试后,所有测试都会失败并出现错误:

错误:无法构造“AudioContext”:提供的硬件上下文数量 (6) 大于或等于最大界限 (6)。

有没有办法让我在测试之间清除 AudioContext?我已经在 afterEach block 中尝试过 AudioPlayer.context.close() ,但似乎不起作用。

服务看起来有点像这样:

angular.module('myApp')
.service('AudioPlayer', function () {

var self = this;

self.context = new AudioContext();

this.doSomething = function () {
// doing super cool testable stuff here
}
})

测试看起来有点像这样:

describe('AudioPlayer', function () {
var AudioPlayer;

beforeEach(function () {
inject(function ($injector) {
AudioPlayer = $injector.get('AudioPlayer');
});
});

afterEach(function () {
AudioPlayer.context.close();
});

it('does cool stuff', function () {
AudioPlayer.doSomething();
// unit test
});

it('does other cool stuff', function () {
AudioPlayer.doSomething();
// unit test
});

});

感谢您的帮助!

这是一个说明问题的 jsFiddle: http://jsfiddle.net/briankeane/cp929can/1/

最佳答案

我最终在测试中创建了一个类似单例的上下文,然后使用返回相同 AudioContext 的函数对构造函数进行 stub ...这是最终的测试代码:

describe('AudioPlayer', function () {
var AudioPlayer;
var context = new AudioContext(); // create the AudioContext once

beforeEach(function () {
module('myApp');

inject(function ($injector) {
spyOn(window, 'AudioContext').and.callFake(function () {
return context; // stub the constructor
});
AudioPlayer = $injector.get('AudioPlayer');
});
});

for (var i=0;i<7;i++) {
it('does cool stuff', function () {
AudioPlayer.doSomething();
expect(true).toBe(true);
// unit test
});
}
});

这是工作 fiddle :http://jsfiddle.net/briankeane/3ctngs1u/

希望这对某人有帮助。

关于javascript - 如何在 Jasmine 测试中释放 AudioContext,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32721728/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com