Files
shumai/packages/webui/hooks/use-video-transcript.test.tsx
T

214 lines
7.1 KiB
TypeScript
Raw Normal View History

// @vitest-environment happy-dom
import type { AssetInfo, TranscriptJobStatus } from '@shumai/dtos'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { act, cleanup, renderHook, waitFor } from '@testing-library/react'
import React from 'react'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { fileTranscriptionStatusKey, useVideoTranscript } from './use-video-transcript'
const mockSignupInfoGet = vi.fn()
const mockTranscriptsGet = vi.fn()
const mockTranscriptionStatusGet = vi.fn()
vi.mock('@/ui/api/client', () => ({
client: {
api: {
'signup-info': {
$get: () => mockSignupInfoGet(),
},
files: {
':fileId': {
transcripts: {
$get: (...args: unknown[]) => mockTranscriptsGet(...args),
},
'transcription-status': {
$get: (...args: unknown[]) => mockTranscriptionStatusGet(...args),
},
},
},
},
},
}))
function createWrapper(queryClient: QueryClient) {
return function Wrapper({ children }: { children: React.ReactNode }) {
return <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
}
}
const readyVideo: AssetInfo = {
id: 'video-1',
name: 'demo.mp4',
status: 'processed',
proxyType: 'video',
media: {
videoTranscodes: [{ key: 'proxies/720p.mp4', resolution: '720p', width: 1280, height: 720 }],
},
} as AssetInfo
describe('useVideoTranscript', () => {
let queryClient: QueryClient
beforeEach(() => {
queryClient = new QueryClient({
defaultOptions: {
queries: { retry: false },
},
})
mockSignupInfoGet.mockResolvedValue({
ok: true,
json: async () => ({ transcriptionEnabled: false }),
})
mockTranscriptsGet.mockResolvedValue({
ok: true,
json: async () => ({ languages: [] }),
})
mockTranscriptionStatusGet.mockResolvedValue({
ok: true,
json: async () => null,
})
})
afterEach(() => {
cleanup()
queryClient.clear()
vi.clearAllMocks()
})
it('hides the toggle when there is no transcript and transcription is disabled', async () => {
const { result } = renderHook(
() => useVideoTranscript(readyVideo, { canEdit: true, projectId: 'proj-1' }),
{ wrapper: createWrapper(queryClient) },
)
await waitFor(() => expect(mockTranscriptsGet).toHaveBeenCalledOnce())
await waitFor(() => expect(mockSignupInfoGet).toHaveBeenCalledOnce())
expect(result.current).toBeUndefined()
expect(mockTranscriptionStatusGet).not.toHaveBeenCalled()
})
it('hides the toggle for read-only users when there is no transcript even if transcription is enabled', async () => {
mockSignupInfoGet.mockResolvedValue({
ok: true,
json: async () => ({ transcriptionEnabled: true }),
})
const { result } = renderHook(
() => useVideoTranscript(readyVideo, { canEdit: false, projectId: 'proj-1' }),
{ wrapper: createWrapper(queryClient) },
)
await waitFor(() => expect(mockTranscriptsGet).toHaveBeenCalledOnce())
expect(result.current).toBeUndefined()
expect(mockSignupInfoGet).not.toHaveBeenCalled()
expect(mockTranscriptionStatusGet).not.toHaveBeenCalled()
})
it('shows the toggle for read-only users when a saved transcript exists', async () => {
mockTranscriptsGet.mockResolvedValue({
ok: true,
json: async () => ({ languages: ['en'] }),
})
const { result } = renderHook(
() => useVideoTranscript(readyVideo, { canEdit: false, projectId: 'proj-1' }),
{ wrapper: createWrapper(queryClient) },
)
await waitFor(() => expect(result.current).toBeDefined())
act(() => result.current?.toggle.onToggle())
expect(result.current?.panel?.languages).toEqual(['en'])
expect(result.current?.panel?.canGenerate).toBe(false)
})
it('shows the empty panel for editors when transcription is enabled and tracks status until completion', async () => {
mockSignupInfoGet.mockResolvedValue({
ok: true,
json: async () => ({ transcriptionEnabled: true }),
})
let savedLanguages: string[] = []
let currentStatus: TranscriptJobStatus | null = null
mockTranscriptsGet.mockImplementation(async () => ({
ok: true,
json: async () => ({ languages: savedLanguages }),
}))
mockTranscriptionStatusGet.mockImplementation(async () => ({
ok: true,
json: async () => currentStatus,
}))
const { result } = renderHook(
() => useVideoTranscript(readyVideo, { canEdit: true, projectId: 'proj-1' }),
{ wrapper: createWrapper(queryClient) },
)
await waitFor(() => expect(result.current).toBeDefined())
act(() => result.current?.toggle.onToggle())
expect(result.current?.panel).toMatchObject({
assetId: 'video-1',
assetName: 'demo.mp4',
languages: [],
canGenerate: true,
canStartGeneration: true,
isTranscribing: false,
})
currentStatus = { status: 'processing', taskId: 'task-1' }
await act(async () => {
await result.current?.panel?.onJobAccepted('video-1')
})
await waitFor(() => expect(result.current?.panel?.isTranscribing).toBe(true))
expect(queryClient.getQueryData(['project-transcription-status', 'proj-1'])).toEqual([
'video-1',
])
savedLanguages = ['en']
currentStatus = { status: 'completed', taskId: 'task-1' }
await act(async () => {
await queryClient.refetchQueries({
queryKey: fileTranscriptionStatusKey('video-1'),
exact: true,
})
})
await waitFor(() => expect(result.current?.panel?.languages).toEqual(['en']))
expect(result.current?.panel?.isTranscribing).toBe(false)
expect(queryClient.getQueryData(['project-transcription-status', 'proj-1'])).toEqual([])
})
it('returns to idle empty state and invalidates comments when a tracked job fails', async () => {
mockSignupInfoGet.mockResolvedValue({
ok: true,
json: async () => ({ transcriptionEnabled: true }),
})
let currentStatus: TranscriptJobStatus | null = { status: 'processing', taskId: 'task-2' }
mockTranscriptionStatusGet.mockImplementation(async () => ({
ok: true,
json: async () => currentStatus,
}))
const invalidateSpy = vi.spyOn(queryClient, 'invalidateQueries')
const { result } = renderHook(
() => useVideoTranscript(readyVideo, { canEdit: true, projectId: 'proj-1' }),
{ wrapper: createWrapper(queryClient) },
)
await waitFor(() => expect(result.current).toBeDefined())
act(() => result.current?.toggle.onToggle())
await waitFor(() => expect(result.current?.panel?.isTranscribing).toBe(true))
currentStatus = { status: 'failed', taskId: 'task-2', reason: 'noAudio' }
await act(async () => {
await queryClient.refetchQueries({
queryKey: fileTranscriptionStatusKey('video-1'),
exact: true,
})
})
await waitFor(() => expect(result.current?.panel?.isTranscribing).toBe(false))
expect(result.current?.panel?.languages).toEqual([])
expect(invalidateSpy).toHaveBeenCalledWith({ queryKey: ['files', 'video-1', 'comments'] })
})
})