javascript – Angular.js单元测试“inject()”在“运行”阶段块之前触发
作者:互联网
我有一个场景,我正在尝试为移动设备加载HTML5音频,这只能通过用户交互(例如ontouchstart)来实现.我已经在Angular运行阶段实现了这个逻辑,以确保它尽早附加.我无法在配置阶段附加它,因为它依赖于其他Angular工厂:
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);
}
}]);
我有以下单元测试失败,因为上面的事件处理程序尚未及时注册:
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');
}]));
我希望run()块在测试开始之前完成执行?这个假设我错了吗?如果是这样,如何解决这种情况最好?
谢谢
解决方法:
该代码看起来与我异步(因为它等待用户交互,一方面),所以使用done()回调:
beforeEach(function (done) { // <--- Add this parameter.
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', {});
done(); // <--- It looks to me like this is where done() should be called.
}]);
module('Html5SoundLoaderApp');
});
您必须对任何异步执行的工作使用done().否则,摩卡只是前进而不等待工作进行.
标签:javascript,angularjs,unit-testing,mocha,karma-runner 来源: https://codeday.me/bug/20190703/1365841.html