如何在Jasmine测试中释放AudioContext

How to Release AudioContext in Jasmine Tests

本文关键字:释放 AudioContext 测试 Jasmine      更新时间:2023-09-26

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

Error: Failed to construct 'AudioContext': The number of hardware contexts provided (6) is greater than or equal to the maximum bound (6).

是否有办法让我清除测试之间的AudioContext ?我已经尝试过AudioPlayer.context.close()在一个afterEach块,但似乎不工作。

service看起来像这样:

angular.module('myApp')
  .service('AudioPlayer', function () {
    var self = this;
    self.context = new AudioContext();
    this.doSomething = function () {
       // doing super cool testable stuff here
    }
  })

and tests看起来像这样:

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的函数来存根构造函数…下面是最终的测试代码:

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
      });
  }
});

这里是工作小提琴:http://jsfiddle.net/briankeane/3ctngs1u/

你可以直接关闭它

    audioCtx.close();

见文档audioContext.close ()