File size: 2,088 Bytes
2f49513
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
import { renderHook } from "@testing-library/react";
import useAudioPlayer from "../useAudioPlayer";

// We don't need to duplicate the MockAudioBuffer class here as it's already in setupTests.ts

describe("useAudioPlayer", () => {
  // Mock bufferSource for specific test needs
  const mockBufferSource = {
    connect: jest.fn(),
    start: jest.fn(),
  };

  // Store the original implementation
  const originalCreateBufferSource =
    global.AudioContext.prototype.createBufferSource;

  // Create a reusable audio buffer
  let audioBuffer: AudioBuffer;
  let shortAudioBuffer: AudioBuffer;

  beforeAll(() => {
    // Override the createBufferSource method for this test suite
    global.AudioContext.prototype.createBufferSource = jest
      .fn()
      .mockReturnValue(mockBufferSource);

    // Create the reusable audio buffers using the globally mocked AudioBuffer
    audioBuffer = new AudioBuffer({
      length: 40000,
      sampleRate: 44100,
      numberOfChannels: 1,
    });

    shortAudioBuffer = new AudioBuffer({
      length: 100,
      sampleRate: 44100,
      numberOfChannels: 1,
    });
  });

  afterAll(() => {
    // Restore the original implementation after tests
    global.AudioContext.prototype.createBufferSource =
      originalCreateBufferSource;
  });

  beforeEach(() => {
    // Reset all mocks before each test
    jest.clearAllMocks();
  });

  test("plays audio chunks", () => {
    const { result } = renderHook(() => useAudioPlayer());

    result.current.play(audioBuffer);

    expect(mockBufferSource.start).toHaveBeenCalled();
  });

  test("doesn't start playing audio chunks until the existing chunks are long enough", () => {
    const { result } = renderHook(() => useAudioPlayer());

    result.current.play(shortAudioBuffer);

    expect(mockBufferSource.start).not.toHaveBeenCalled();

    // Add many chunks of audio, which makes the total buffered audio long enough to start
    for (let i = 0; i < 1000; i++) {
      result.current.play(shortAudioBuffer);
    }

    expect(mockBufferSource.start).toHaveBeenCalled();
  });
});