0

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?

glend
  • 1,592
  • 1
  • 17
  • 36

1 Answers1

3

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.

chrisguttandin
  • 7,025
  • 15
  • 21
  • how do i reset it? – glend Dec 03 '21 at 06:07
  • 1
    Do you mean how you remove it again from the global object? I would expect `delete global.AudioContext` to work. – chrisguttandin Dec 03 '21 at 08:53
  • `global.AudioContext = AudioContext;` and `delete global.AudioContext` generate typescript errors. – glend Dec 03 '21 at 13:33
  • The `delete` error was happening because `global.AudioContext` was being set to `undefined` to resolve this, I saved a reference to the function and restored it after I was done with that test. – glend Dec 03 '21 at 14:00