0

我有一个设置 audioContext 的 Angular 服务。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 块中尝试过,但似乎没有工作。

服务看起来有点像这样:

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/

4

2 回答 2

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/

希望这可以帮助某人。

于 2015-09-23T13:37:15.380 回答
1

你可以关闭它。

    audioCtx.close();

请参阅文档 audioContext.close()

于 2017-09-23T21:13:30.513 回答