Open History to see the last commit
1import { InternalFormApi } from '@tanstack/form-core/internals'
2import { describe, expect, it, vi } from 'vitest'
3import { createMountedFormsController } from '../src/bridge/forms/mountedForms'
4import { formDevtoolsEventClient } from '../src/eventClient.lib'
5import { connectTestEventBus } from './testEventBus'
6β
7describe('mounted forms bridge', () => {
8 it('tracks duplicate mounts until the final unmount', () => {
9 const disconnectEventBus = connectTestEventBus()
10 const mountedForms = createMountedFormsController()
11 const form = new InternalFormApi({
12 formId: 'profile',
13 defaultValues: { name: '' },
14 })
15 const onFinalUnmount = vi.fn()
16β
17 try {
18 expect(mountedForms.mountForm(form)).toBe(true)
19 expect(mountedForms.mountForm(form)).toBe(false)
20β
21 const { instanceId } = mountedForms.getMountedFormsSnapshot()[0]!
22 expect(mountedForms.getMountedForm(instanceId)).toBe(form)
23β
24 expect(mountedForms.unmountForm(form, onFinalUnmount)).toBe(false)
25 expect(onFinalUnmount).not.toHaveBeenCalled()
26 expect(mountedForms.getMountedFormsSnapshot()).toHaveLength(1)
27β
28 expect(mountedForms.unmountForm(form, onFinalUnmount)).toBe(true)
29 expect(onFinalUnmount).toHaveBeenCalledWith(instanceId)
30 expect(mountedForms.getMountedForm(instanceId)).toBeUndefined()
31 expect(mountedForms.getMountedFormsSnapshot()).toEqual([])
32 } finally {
33 mountedForms.dispose()
34 disconnectEventBus()
35 }
36 })
37β
38 it('updates mounted-form labels and responds to snapshot requests', () => {
39 const disconnectEventBus = connectTestEventBus()
40 const mountedForms = createMountedFormsController()
41 const form = new InternalFormApi({
42 formId: 'profile',
43 defaultValues: { name: '' },
44 })
45 const snapshots: Array<Array<string>> = []
46 const cleanupSnapshotListener = formDevtoolsEventClient.on(
47 'mounted-forms-changed',
48 (event) => {
49 snapshots.push(event.payload.forms.map((item) => item.label))
50 },
51 )
52β
53 try {
54 mountedForms.mountForm(form)
55 form._update({
56 formId: 'renamed-profile',
57 defaultValues: { name: '' },
58 })
59 mountedForms.updateForm(form)
60β
61 snapshots.length = 0
62 formDevtoolsEventClient.emit('request-mounted-forms', {})
63β
64 expect(snapshots).toEqual([['renamed-profile']])
65 } finally {
66 cleanupSnapshotListener()
67 mountedForms.dispose()
68 disconnectEventBus()
69 }
70 })
71})