Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

inject-audio-recorder.test.ts

145 lines4.6 KB

1import { Component } from '@angular/core'
2import { getTestBed, TestBed } from '@angular/core/testing'
3import {
4 BrowserDynamicTestingModule,
5 platformBrowserDynamicTesting,
6} from '@angular/platform-browser-dynamic/testing'
7import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
8// The Angular plugin runs vitest.setup.ts in a separate module realm, so the
9// jsdom Blob polyfill must be imported into this test's own graph rather than
10// via setupFiles (see packages/ai-client/tests/blob-polyfill.ts).
11import '../../ai-client/tests/blob-polyfill'
12import { injectAudioRecorder } from '../src/inject-audio-recorder'
13import type { InjectAudioRecorderResult } from '../src/inject-audio-recorder'
14import type { AudioRecording } from '@tanstack/ai-client'
15​
16// Ensure TestBed is initialized in this module's scope, regardless of whether
17// the setup file's initialization was in a different module context (possible
18// when the Angular plugin creates separate ESM module instances for compiled
19// and setup files in Vitest).
20const testBedInstance = getTestBed() as any
21if (
22 testBedInstance._compiler === null ||
23 testBedInstance._compiler === undefined
24) {
25 getTestBed().initTestEnvironment(
26 BrowserDynamicTestingModule,
27 platformBrowserDynamicTesting(),
28 )
30​
31class FakeMediaRecorder {
32 ondataavailable: ((e: { data: Blob }) => void) | null = null
33 onstop: (() => void) | null = null
34 onerror: (() => void) | null = null
35 state: 'inactive' | 'recording' = 'inactive'
36 constructor(
37 public stream: any,
38 public options?: { mimeType?: string },
39 ) {}
40 get mimeType(): string {
41 return this.options?.mimeType ?? 'audio/webm'
42 }
43 start(): void {
44 this.state = 'recording'
45 }
46 stop(): void {
47 this.state = 'inactive'
48 this.ondataavailable?.({ data: new Blob([new Uint8Array([1, 2, 3])]) })
49 this.onstop?.()
50 }
52​
53beforeEach(() => {
54 vi.stubGlobal('navigator', {
55 mediaDevices: {
56 getUserMedia: vi.fn(async () => ({
57 getTracks: () => [{ stop: vi.fn() }],
58 })),
59 },
60 })
61 vi.stubGlobal('MediaRecorder', FakeMediaRecorder)
62})
63​
64afterEach(() => {
65 vi.unstubAllGlobals()
66})
67​
68function renderInjectAudioRecorder(options?: any) {
69 @Component({ standalone: true, template: '' })
70 class Host {
71 rec = injectAudioRecorder(options)
72 }
73 const fixture = TestBed.createComponent(Host)
74 fixture.detectChanges()
75 return {
76 get result(): InjectAudioRecorderResult<AudioRecording> {
77 return fixture.componentInstance
78 .rec as InjectAudioRecorderResult<AudioRecording>
79 },
80 flush: () => fixture.detectChanges(),
81 destroy: () => fixture.destroy(),
82 }
84​
85describe('injectAudioRecorder', () => {
86 it('toggles isRecording and resolves a recording', async () => {
87 const { result } = renderInjectAudioRecorder()
88 expect(result.isSupported).toBe(true)
89 expect(result.isRecording()).toBe(false)
90​
91 await result.start()
92 expect(result.isRecording()).toBe(true)
93​
94 const rec = await result.stop()
95 expect(result.isRecording()).toBe(false)
96 expect(rec.base64).toBe('AQID')
97 expect(rec.part.type).toBe('audio')
98 expect(result.recording()?.base64).toBe('AQID')
99 })
100​
101 it('applies the onComplete transform to stop() and recording()', async () => {
102 const { result } = renderInjectAudioRecorder({
103 onComplete: (r: any) => r.base64,
104 })
105 await result.start()
106 const out = await result.stop()
107 expect(out).toBe('AQID')
108 expect(result.recording()).toBe('AQID')
109 })
110​
111 it('surfaces a getUserMedia rejection through onError and rejects start()', async () => {
112 const denied = new Error('Permission denied')
113 vi.stubGlobal('navigator', {
114 mediaDevices: { getUserMedia: vi.fn(async () => Promise.reject(denied)) },
115 })
116 const onError = vi.fn()
117 const { result } = renderInjectAudioRecorder({ onError })
118​
119 await expect(result.start()).rejects.toThrow('Permission denied')
120 expect(onError).toHaveBeenCalledWith(denied)
121 expect(result.isRecording()).toBe(false)
122 })
123​
124 it('releases the mic on component destroy', async () => {
125 const trackStop = vi.fn()
126 vi.stubGlobal('navigator', {
127 mediaDevices: {
128 getUserMedia: vi.fn(async () => ({
129 getTracks: () => [{ stop: trackStop }],
130 })),
131 },
132 })
133 const { result, destroy } = renderInjectAudioRecorder()
134 await result.start()
135 expect(result.isRecording()).toBe(true)
136 // DestroyRef.onDestroy() should cancel the in-flight recording and stop the
137 // microphone tracks so the mic indicator clears.
138 destroy()
139 expect(trackStop).toHaveBeenCalled()
140 })
141​
142 it('throws outside an injection context', () => {
143 expect(() => injectAudioRecorder()).toThrow()
144 })
145})