Search code examples
angulartypescriptunit-testingkarma-jasmineupgrade

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


I recently upgraded my application from angular 10 to 11 and then when i run unit test for the application I'm getting this error and the tests terminate. It happens most of the time but sometime no error pops up and tests run as usual. Any pointers as to how this can be resolved.

error

Happens only when unit test is run whereas application runs fine with no errors


Solution

  • The main problem problem with this was that it was really difficult to find out in which component or service this error was present. Also that sometimes test would run without any errors.

    I did a global search for "play()" which was the root cause of the problem.

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

    This is the code snippet which was causing the problem and specifically audio.play(). There is two approach we can take here:

    1. mock the above function call
    2. add below code snippet before audio.play() statement (not sure if this method is correct as we are altering the typescript file which can cause errors in the application)
    audio.muted=true;
    audio.autoplay=true;
    

    I chose the first approach...the former being simple and easy.Doing something like this

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

    Mocking the function everytime it would be called.