Open History to see the last commit
1import type { TranscriptionResult } from "@react-native-ai/apple/src/NativeAppleTranscription";
2import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
3
4import { VoiceTranscriptionError } from "@t3tools/client-runtime/voice-input";
5
6const mocks = vi.hoisted(() => ({
7 isAvailable: vi.fn<(locale: string) => boolean>(),
8 prepare: vi.fn<(locale: string) => Promise<string>>(),
9 transcribe: vi.fn<(audio: ArrayBufferLike, locale: string) => Promise<TranscriptionResult>>(),
10 readAudio: vi.fn<() => Promise<ArrayBuffer>>(),
11}));
12
13vi.mock("@react-native-ai/apple/src/NativeAppleTranscription", () => ({
14 default: {
15 isAvailable: mocks.isAvailable,
16 prepare: mocks.prepare,
17 transcribe: mocks.transcribe,
18 },
19}));
20
21vi.mock("expo-file-system", () => ({
22 File: class {
23 arrayBuffer = mocks.readAudio;
24 },
25}));
26
27import { getLocalVoiceTranscriber } from "./voiceTranscription.ios";
28
29const audio = new ArrayBuffer(4);
30const nativeTranscript: TranscriptionResult = {
31 duration: 2,
32 segments: [
33 { text: " Hej", startSecond: 0, endSecond: 1 },
34 { text: "världen. ", startSecond: 1, endSecond: 2 },
35 ],
36};
37
38function deferred<T>() {
39 let resolve!: (value: T) => void;
40 const promise = new Promise<T>((next) => {
41 resolve = next;
42 });
43 return { promise, resolve };
44}
45
46beforeEach(() => {
47 vi.resetAllMocks();
48 mocks.isAvailable.mockReturnValue(true);
49 mocks.prepare.mockResolvedValue("sv-SE");
50 mocks.readAudio.mockResolvedValue(audio);
51 mocks.transcribe.mockResolvedValue(nativeTranscript);
52});
53
54afterEach(() => {
55 vi.restoreAllMocks();
56});
57
58describe("getLocalVoiceTranscriber", () => {
59 it("does not start native transcription after cancellation during a file read", async () => {
60 const enteredRead = deferred<void>();
61 const readResult = deferred<ArrayBuffer>();
62 mocks.readAudio.mockImplementation(() => {
63 enteredRead.resolve();
64 return readResult.promise;
65 });
66 const controller = new AbortController();
67 const options = { signal: controller.signal };
68 const prepared = await getLocalVoiceTranscriber()!.prepare(options);
69 const result = prepared
70 .transcribe("file:///voice.m4a", options)
71 .catch((error: unknown) => error);
72
73 await enteredRead.promise;
74 controller.abort();
75 readResult.resolve(audio);
76
77 const error = await result;
78 expect(error).toBeInstanceOf(VoiceTranscriptionError);
79 expect(error).toMatchObject({ code: "cancelled" });
80 expect(mocks.transcribe).not.toHaveBeenCalled();
81 });
82});