Unhandled promise rejection: NotAllowedError: play() failed because the user didn't interact with the document first

Unhandled promise rejection: NotAllowedError: play() failed because the user didn't interact with the document first

我最近将我的应用程序从 angular 10 升级到 11,然后当我 运行 对应用程序进行单元测试时,我收到此错误并且测试终止。它大部分时间都会发生,但有时不会弹出错误并像往常一样测试 运行。关于如何解决这个问题的任何指示。

error

仅当单元测试为 运行 时发生,而应用程序 运行 正常且没有错误

这个问题的主要问题是很难找出这个错误出现在哪个组件或服务中。此外,有时测试 运行 没有任何错误。

我对“play()”进行了全局搜索,这是问题的根本原因。

playAlertSound(){
const audio=new Audio()
audio.src= /* audio source link */
audio.load()
audio.play()
}

这是导致问题的代码片段,特别是 audio.play()。我们可以采用两种方法:

  1. 模拟上面的函数调用
  2. 在 audio.play() 语句之前添加以下代码片段(不确定此方法是否正确,因为我们正在更改打字稿文件,这可能会导致应用程序出错)
audio.muted=true;
audio.autoplay=true;

我选择了第一种方法...前者很简单 easy.Doing 类似这样

spyOn(component,'playAlertSound').and.callFake(()=>{})

每次调用函数时都对其进行模拟。