unit-testingjestjsmockingaudiocontext

mocking AudioContext() in Jest


I have the following code inside a function in my project;

....
if (state.context == null) {
    return {
        ...state,
        context: new AudioContext()
    }
}
....

I'm trying to test this behaviour in Jest. However, Jest uses jsdom which doesn't support AudioContext()

In other tests I use;

.....
jest.spyOn(global.Math, 'random').mockReturnValue(0.3);
....
jest.spyOn(global.Math, 'random').mockRestore();
....

This doesn't work. When I call spyOn(global /* or window */, 'AudioContext') I get the error Cannot spy the AudioContext property because it is not a function; undefined given instead

I have also found this library which seems like it might work except that it requires you to use the mocked version of the function in the code, rather than overloading it as I have been doing with random().

I would replace jsdom as my test environment, however, I haven't been able to find one that supports AudioContext().

Is there a solution whereby I don't alter my source code? Passing into the function that calls AudioContext() a mocked or functional AudioContext at runtime?


Solution

  • I'm the author of the library mentioned in the question. I think the following should work.

    import { AudioContext } from 'standardized-audio-context-mock';
    
    global.AudioContext = AudioContext;
    

    However, I'm not a Jest user myself. Please let me know if it doesn't work and feel free to open an issue for any bug you encounter.