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

test-utils.ts

94 lines2.5 KB

1import { Component } from '@angular/core'
2import { TestBed, getTestBed } from '@angular/core/testing'
3import {
4 BrowserDynamicTestingModule,
5 platformBrowserDynamicTesting,
6} from '@angular/platform-browser-dynamic/testing'
7import { injectChat } from '../src/inject-chat'
8import type { InjectChatOptions, InjectChatResult } from '../src/types'
9​
10export {
11 createMockConnectionAdapter,
12 createTextChunks,
13 createToolCallChunks,
14} from '../../ai-client/tests/test-utils'
15​
16export function createInterruptResumeSnapshot() {
17 const pendingInterrupts = [
18 {
19 id: 'staged-interrupt',
20 reason: 'confirmation',
21 metadata: {
22 'tanstack:interruptBinding': {
23 kind: 'generic' as const,
24 interruptId: 'staged-interrupt',
25 interruptedRunId: 'run-1',
26 generation: 1,
27 responseSchemaHash: 'none',
28 },
29 },
30 },
31 {
32 id: 'invalid-interrupt',
33 reason: 'confirmation',
34 metadata: {
35 'tanstack:interruptBinding': {
36 kind: 'generic' as const,
37 interruptId: 'invalid-interrupt',
38 interruptedRunId: 'run-1',
39 generation: 1,
40 responseSchemaHash: 'none',
41 },
42 },
43 },
44 ]
45​
46 return {
47 resumeState: { threadId: 'thread-1', runId: 'run-1' },
48 pendingInterrupts,
49 }
51​
52// Ensure TestBed is initialized in this module's scope, regardless of whether
53// the setup file's initialization was in a different module context (possible
54// when the Angular plugin creates separate ESM module instances for compiled
55// and setup files in Vitest).
56const testBedInstance = getTestBed() as any
57if (
58 testBedInstance._compiler === null ||
59 testBedInstance._compiler === undefined
60) {
61 getTestBed().initTestEnvironment(
62 BrowserDynamicTestingModule,
63 platformBrowserDynamicTesting(),
64 )
66​
67/**
68 * Mount `injectChat` inside a real component so injection context,
69 * `afterNextRender`, and `DestroyRef` behave as in an app. Returns a live
70 * `result` accessor plus `flush` (runs change detection) and `destroy`.
71 */
72export function renderInjectChat<T extends InjectChatOptions>(
73 options?: T,
74): {
75 result: InjectChatResult
76 flush: () => void
77 destroy: () => void
78} {
79 @Component({ standalone: true, template: '' })
80 class HostComponent {
81 chat = injectChat(options as any)
82 }
83​
84 const fixture = TestBed.createComponent(HostComponent)
85 fixture.detectChanges()
86​
87 return {
88 get result() {
89 return fixture.componentInstance.chat
90 },
91 flush: () => fixture.detectChanges(),
92 destroy: () => fixture.destroy(),
93 }