// @vitest-environment jsdom import { act } from 'react' import { createRoot, type Root } from 'react-dom/client' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { PPConnection } from './PPConnection' let root: Root, host: HTMLDivElement let fetcher: ReturnType Promise>> const active = { id: 'active-one', base_url: 'https://api.example.invalid', username: 'example', password_configured: true, } const view = { revision: 1, active, pending: null, observation: { state: 'valid', message: '认证有效 · 目录可读', checked_at: '2026-11-17T10:00:00Z' }, pending_observation: null, } const json = (data: unknown) => new Response(JSON.stringify({ data })) const click = async (label: string) => { const b = [...host.querySelectorAll('button')].find((x) => x.textContent?.trim() === label) expect(b, label).toBeTruthy() await act(async () => b!.click()) } const type = async (label: string, value: string) => { const input = [...host.querySelectorAll('label')] .find((x) => x.textContent?.startsWith(label)) ?.querySelector('input') expect(input, label).toBeTruthy() await act(async () => { Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')!.set!.call(input, value) input!.dispatchEvent(new Event('input', { bubbles: true })) }) } beforeEach(() => { Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true }) host = document.createElement('div') document.body.append(host) root = createRoot(host) fetcher = vi.fn(async (_p: string, init?: RequestInit) => json(init?.method === 'PUT' ? { ...view, revision: 2 } : view) ) vi.stubGlobal('fetch', fetcher) }) afterEach(async () => { await act(async () => root.unmount()) host.remove() vi.unstubAllGlobals() }) describe('PP configuration editor', () => { it('keeps the stored password without sending a masked replacement or launching scans', async () => { await act(async () => root.render()) await click('配置') expect(host.querySelector('input[type=password]')).toBeNull() await click('保存并校验') const writes = fetcher.mock.calls.filter(([, i]) => i?.method === 'PUT') expect(writes).toHaveLength(1) const data = JSON.parse(String(writes[0][1]?.body)) expect(data).toEqual({ base_url: active.base_url, username: 'example', revision: 1 }) expect(host.textContent).toContain('已保存并生效') expect(fetcher.mock.calls.every(([p]) => p.startsWith('/api/v1/pp-connection'))).toBe(true) }) it('sends a newly entered password only on explicit replacement and clears it after save', async () => { await act(async () => root.render()) await click('配置') await click('更新密码') await type('新密码', 'example-replacement') await click('保存并校验') const write = fetcher.mock.calls.find(([, i]) => i?.method === 'PUT') expect(JSON.parse(String(write?.[1]?.body)).password).toBe('example-replacement') expect(host.querySelector('input[type=password]')).toBeNull() expect(host.textContent).not.toContain('example-replacement') }) })