I am facing a situation where I need to load HTML5 Audio specifically for mobile devices, which requires user interaction like ontouchstart. To achieve this, I have implemented the necessary logic in an Angular run phase to ensure it is executed at the earliest opportunity. Since it has dependencies on other Angular factories, I cannot attach it in the config phase:
angular.module('MyModule')
.run(['Device', 'ResourceManager', 'ExceptionFactory', function (Device, ResourceManager, ExceptionFactory) {
if (!Device.browser.features.webaudio) {
var onFirstUserInteraction = function () {
var sounds = ResourceManager.getSounds();
if (sounds.length > 1) {
throw ExceptionFactory.create('Html5AudioLimitReachedException', 'Html5 Audio Devices can only load one sound resource');
}
if (sounds.length === 1) {
sounds[0].createBrowserAudioObject();
}
document.documentElement.removeEventListener(Device.browser.is.IE ? 'click' : 'touchstart', onFirstUserInteraction, true);
};
document.documentElement.addEventListener(Device.browser.is.IE ? 'click' : 'touchstart', onFirstUserInteraction, true);
}
}]);
A specific unit test is failing because the event handler mentioned above has not been registered in time:
beforeEach(function () {
angular.module('Html5SoundLoaderApp', [])
.run(['Device', 'ResourceManager', function (Device, ResourceManager) {
Device.browser.features.webaudio = false;
ResourceManager.addSound('testOne', 'test/url/testOne.mp3', {});
ResourceManager.addSound('testTwo', 'test/url/testTwo.mp3', {});
}]);
module('Html5SoundLoaderApp');
});
it('should only be able to load one sound resource', inject(['ExceptionFactory', function (ExceptionFactory) {
var spy = sinon.spy(ExceptionFactory, 'create');
expect(function () {
angular.mock.ui.trigger(document.documentElement, 'touchstart')
}).to.throw();
spy.should.have.been.calledOnce;
spy.should.have.been.calledWith('Html5AudioLimitReachedException', 'Html5 Audio Devices can only load one sound resource');
}]));
I assumed that the run() block would complete execution before the test started. Was my assumption incorrect? If so, what would be the best approach to handle this scenario?
Thank you