test(ui): the first mocked IPC, the first store test, the first screen test

TESTING §2 asks for "IPC mocked at the typed wrapper layer" and nothing did it.
No store had a test and no screen had one either — every existing L3 test drives
a leaf component through props. S5 is the slice that needs all three, so it
establishes them.

`ui/src/test/ipc.ts` exports a **factory** each file passes to its own
`vi.mock`, rather than a module that registers the mock as a side effect:
`vi.mock` is hoisted within the file being transformed and only that file, so a
side-effecting module would work or not depending on where the lint's import sort
happened to put it. The factory imports lazily for the same hoist reason.
`isPdError` is the real predicate, not a spy — both stores route every rejection
through it, and a stub would make each error test agree with itself.

`ui/src/test/stores.ts` resets a store between cases. They are module singletons
created at import, so without it the second test inherits the first, and that
failure passes alone and fails in a suite depending on file order.

jsdom parses `<dialog>` and implements none of it, so `showModal` and `close` are
stubbed beside the existing ResizeObserver stubs. They track `open` only, which
means the **modality is not under test** — the top layer, the inert backdrop and
focus containment are the browser's. What is covered is the policy on top: which
control is focused, which is first, and what each calls. The rest is the manual
pass, and the comment says so rather than letting a green suite imply otherwise.

The dialog test asserts both of the slice's exit criteria — the sentence names
each dependent *and* its constraint, and widening calls the guard again with no
execute in between — against the generated `guard_report.json`, so the guard's
own rules cannot drift away from what is asserted while both stay green.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
poli0981andClaude Opus 5 committed 2026-08-09 21:46:25 +07:00
1 parent 980bd5d750
commit f5badf2750
6 files changed
+489

No files matched your search

@@ -0,0 +1,93 @@
/**
* The guard dialog — DATA-FLOW §5's three options, and UI-SPEC §7's focus rule.
*
* The `GuardReport` is the **generated** fixture, computed in Rust by running the real graph over
* the real `pkg_list()` scenario. Hand-writing one would let the guard's own rules drift away from
* what this asserts while both stayed green.
*/
import { fireEvent, render, screen, within } from '@testing-library/react'
import { describe, expect, it, vi } from 'vitest'
import { PdUninstallDialog } from '@/components/PdUninstallDialog'
import type { GuardReport } from '@/ipc'
import guardFixture from '@/test/fixtures/guard_report.json'
const BREAKING = guardFixture as GuardReport
/** The same removal with nothing depending on it. */
const CLEAR: GuardReport = { removing: ['certifi'], breaks: {}, withDependents: ['certifi'] }
function setup(report: GuardReport, overrides: { busy?: boolean } = {}) {
const props = {
report,
busy: overrides.busy ?? false,
onCancel: vi.fn(),
onWiden: vi.fn(),
onConfirm: vi.fn(),
}
render(<PdUninstallDialog {...props} />)
return props
}
/** jsdom implements `showModal`, so the dialog's own subtree is where we look. */
function dialog() {
return screen.getByRole('dialog')
}
describe('PdUninstallDialog', () => {
it('names each dependent and the constraint it declared', () => {
// The slice's exit criterion, and the reason `GuardReport.breaks` carries specifiers at all: a
// list of names says what breaks and not whether the user can live with it.
setup(BREAKING)
expect(screen.getByText('pandas 2.1.4 requires numpy<2,>=1.26.0')).toBeInTheDocument()
expect(screen.getByText('scipy 1.11.4 requires numpy<1.28.0,>=1.21.6')).toBeInTheDocument()
})
it('focuses Cancel, and renders it first', () => {
// UI-SPEC §7: destructive confirms "require the dialog's default focus to be Cancel".
setup(BREAKING)
const cancel = within(dialog()).getByText('Cancel')
expect(cancel).toHaveFocus()
const buttons = within(dialog()).getAllByRole('button')
expect(buttons[0]).toBe(cancel)
})
it('re-guards rather than proceeding when the dependents are added', () => {
// The other exit criterion. Widening must go back through the guard, because pulling one
// dependent in can break a third package — proceeding here is the bare-`pip uninstall`
// behaviour the guard exists to replace.
const { onWiden, onConfirm } = setup(BREAKING)
fireEvent.click(within(dialog()).getByText(/Remove the dependents too/))
expect(onWiden).toHaveBeenCalledOnce()
expect(onConfirm).not.toHaveBeenCalled()
})
it('forces only when the user chose to break things', () => {
const { onConfirm } = setup(BREAKING)
fireEvent.click(within(dialog()).getByText(/Remove anyway/))
expect(onConfirm).toHaveBeenCalledWith(true)
})
it('does not force a removal that breaks nothing', () => {
// `force` is an acknowledgement of breakage, not a synonym for confirm. Sending `true` here
// would waive a guard that never objected.
const { onConfirm } = setup(CLEAR)
expect(within(dialog()).queryByText(/Remove anyway/)).not.toBeInTheDocument()
fireEvent.click(within(dialog()).getByText(/^Remove 1 package$/))
expect(onConfirm).toHaveBeenCalledWith(false)
})
it('disables every control while a re-guard is in flight', () => {
const { onWiden, onConfirm } = setup(BREAKING, { busy: true })
for (const button of within(dialog()).getAllByRole('button')) {
expect(button).toBeDisabled()
}
fireEvent.click(within(dialog()).getByText(/Remove anyway/))
expect(onWiden).not.toHaveBeenCalled()
expect(onConfirm).not.toHaveBeenCalled()
})
})
+127
View File
@@ -0,0 +1,127 @@
/**
* The Pins screen — the repo's first *screen* test.
*
* Leaf components take props; a screen reads a store and calls commands, so this is the first test
* that has to mock `@/ipc` and reset a store between cases. The pin fixture is generated from the
* real Rust types, so a field renamed in `pins.rs` fails here rather than drifting.
*/
import { fireEvent, render, screen } from '@testing-library/react'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import * as ipc from '@/ipc'
import type { Pin } from '@/ipc'
import { PdPins } from '@/screens/PdPins'
import { useEnvStore } from '@/stores'
import pinFixture from '@/test/fixtures/pin_list.json'
import { resetStore } from '@/test/stores'
vi.mock('@/ipc', async () => {
const { ipcMock } = await import('@/test/ipc')
return ipcMock()
})
const PINS = pinFixture as Pin[]
/** Put the store where it would be after an environment was selected and loaded. */
function withEnv(pins: Pin[] = PINS) {
useEnvStore.setState({
selected: 'C:\\venv\\Scripts\\python.exe',
loadedFor: 'C:\\venv\\Scripts\\python.exe',
rows: [
{
interpreter: 'C:\\venv\\Scripts\\python.exe',
envHash: 'envhash01',
source: 'manual',
} as never,
],
pins,
})
}
describe('PdPins', () => {
beforeEach(() => {
vi.clearAllMocks()
resetStore(useEnvStore)
})
it('says there is no list, not an empty one, without an environment', () => {
// Pins are keyed by `envHash`. "No pins" here would read as "this environment has none".
render(<PdPins />)
// `PdEmptyState` prefixes the mono glyph UI-SPEC §7 asks for, so this is a substring match.
expect(screen.getByText(/no environment selected/)).toBeInTheDocument()
})
it('renders one row per pin, telling the two modes apart', () => {
withEnv()
render(<PdPins />)
// The fixture holds a Hold on numpy and an Exclude on scipy — §4 says only "a 🔒 chip", but a
// Hold restates a version in every plan and an Exclude does not.
expect(document.querySelector('[data-pin="numpy"]')).not.toBeNull()
expect(document.querySelector('[data-pin="scipy"]')).not.toBeNull()
expect(screen.getByText('1.26.4')).toBeInTheDocument()
expect(screen.getByText('pinned')).toBeInTheDocument()
})
it('shows an existing reason and commits an edit on blur', async () => {
withEnv()
render(<PdPins />)
const field = screen.getByLabelText('Reason for pinning numpy')
expect(field).toHaveValue('scipy 1.11.4 needs numpy < 1.28')
fireEvent.change(field, { target: { value: ' pinned for the 2.x migration ' } })
// Not on change: one `pin_add` upsert per keystroke is a lot of SQLite for a text field.
expect(ipc.pinAdd).not.toHaveBeenCalled()
fireEvent.blur(field)
await vi.waitFor(() => {
expect(ipc.pinAdd).toHaveBeenCalledWith('envhash01', {
pkg: 'numpy',
// The mode is carried through untouched: changing what a pin *is* must not be a side
// effect of typing in its reason box.
mode: { hold: { version: '1.26.4' } },
reason: 'pinned for the 2.x migration',
})
})
})
it('clears a reason as null rather than an empty string', async () => {
withEnv()
render(<PdPins />)
const field = screen.getByLabelText('Reason for pinning numpy')
fireEvent.change(field, { target: { value: ' ' } })
fireEvent.blur(field)
// `exactOptionalPropertyTypes` is on and `reason` is optional, so `''` would round-trip as a
// reason that exists and says nothing.
await vi.waitFor(() => {
expect(ipc.pinAdd).toHaveBeenCalledWith('envhash01', {
pkg: 'numpy',
mode: { hold: { version: '1.26.4' } },
})
})
})
it('unpins through the same path the table uses', async () => {
withEnv()
render(<PdPins />)
const row = document.querySelector('[data-pin="scipy"]')
fireEvent.click(row?.querySelector('[data-action="unpin"]') as HTMLElement)
await vi.waitFor(() => {
expect(ipc.pinRemove).toHaveBeenCalledWith('envhash01', 'scipy')
})
})
it('offers no way to create a Hold pin', () => {
// `pins::hold_requirements` is dead code and `plan_requirements` restates the *installed*
// version, so a hold at another version is a promise nothing keeps. The CLI cannot create one
// either; the screen must not be the head that disagrees.
withEnv()
render(<PdPins />)
expect(screen.queryByText(/hold/i)).not.toBeInTheDocument()
})
})
+153
View File
@@ -0,0 +1,153 @@
/**
* `usePlanStore` — the repo's first store test, and the first use of the `@/ipc` mock.
*
* The store deliberately does not re-implement DATA-FLOW's state machine; the flow lives in Rust
* and is resumable. What *is* here, and what these assert, is which command each transition sends
* and which phase the screen is left in — the two things a component test cannot see and a Rust
* test cannot either.
*/
import { beforeEach, describe, expect, it, vi } from 'vitest'
import * as ipc from '@/ipc'
import type { GuardReport, PyEnv } from '@/ipc'
import { PANEL_PHASES, usePlanStore } from '@/stores/plan'
import { resetStore } from '@/test/stores'
// The factory imports lazily because `vi.mock` is hoisted above every import in this file — a
// top-level `ipcMock` reference would be read before it is initialized.
vi.mock('@/ipc', async () => {
const { ipcMock } = await import('@/test/ipc')
return ipcMock()
})
const ENV: PyEnv = {
interpreter: 'C:\\venv\\Scripts\\python.exe',
prefix: 'C:\\venv',
pythonVersion: '3.12.4',
externallyManaged: false,
hiddenUserSite: null,
source: 'manual',
}
const BREAKING: GuardReport = {
removing: ['numpy'],
breaks: { numpy: [{ pkg: 'pandas', version: '2.1.4', constraint: '<2,>=1.26.0' }] },
withDependents: ['numpy', 'pandas'],
}
const CLEAR: GuardReport = { removing: ['numpy', 'pandas'], breaks: {}, withDependents: [] }
describe('usePlanStore', () => {
beforeEach(() => {
vi.clearAllMocks()
resetStore(usePlanStore)
})
it('opens the guard without touching the screen behind it', async () => {
vi.mocked(ipc.uninstallGuard).mockResolvedValue(BREAKING)
await usePlanStore.getState().startUninstall(ENV, ['numpy'])
const { phase, guard, kind } = usePlanStore.getState()
expect(phase).toBe('guard')
expect(kind).toBe('uninstall')
expect(guard).toEqual(BREAKING)
// `guard` is not a panel phase: the dialog opens *over* the table the user selected from, so
// they can still see what they picked while deciding.
expect(PANEL_PHASES.has(phase)).toBe(false)
})
it('re-guards the widened set instead of removing it', async () => {
// The slice's exit criterion, at the layer that decides it. A dependent of a dependent has to
// surface on the next pass, so widening is another `uninstall_guard` and never an execute.
vi.mocked(ipc.uninstallGuard).mockResolvedValueOnce(BREAKING).mockResolvedValueOnce(CLEAR)
await usePlanStore.getState().startUninstall(ENV, ['numpy'])
await usePlanStore.getState().widen()
expect(ipc.uninstallGuard).toHaveBeenCalledTimes(2)
expect(ipc.uninstallGuard).toHaveBeenLastCalledWith(ENV, ['numpy', 'pandas'])
expect(ipc.uninstallExecute).not.toHaveBeenCalled()
expect(usePlanStore.getState().phase).toBe('guard')
expect(usePlanStore.getState().guard).toEqual(CLEAR)
})
it('carries the force acknowledgement through to the command', async () => {
vi.mocked(ipc.uninstallGuard).mockResolvedValue(BREAKING)
vi.mocked(ipc.uninstallExecute).mockResolvedValue({
summary: {
planId: 'uninstall-abc',
phase: 'isolated',
results: [],
check: { ok: true, findings: [] },
counts: { ok: 1, failed: 0, skipped: 0 },
cancelled: false,
},
})
await usePlanStore.getState().startUninstall(ENV, ['numpy'])
await usePlanStore.getState().confirmUninstall(true)
expect(ipc.uninstallExecute).toHaveBeenCalledWith(true)
expect(usePlanStore.getState().phase).toBe('summary')
})
it('lands a failed resolve somewhere the user can see it', async () => {
// The S3/S4 hole: this used to set `idle`, which un-mounts the only thing that renders
// `error`. The phase has to stay inside PANEL_PHASES or the failure is invisible.
vi.mocked(ipc.planResolve).mockRejectedValue({
code: 'PD-RES-003',
message: 'a plan is already resolving or executing',
})
await usePlanStore.getState().resolve(ENV, {
intent: 'update',
all: true,
pkgs: [],
except: [],
forceLatest: false,
})
const { phase, error } = usePlanStore.getState()
expect(phase).toBe('failed')
expect(PANEL_PHASES.has(phase)).toBe(true)
expect(error?.code).toBe('PD-RES-003')
})
it('leaves a failed guard visible too', async () => {
vi.mocked(ipc.uninstallGuard).mockRejectedValue({
code: 'PD-ENV-002',
message: 'this Python is externally managed (PEP 668)',
})
await usePlanStore.getState().startUninstall(ENV, ['numpy'])
expect(usePlanStore.getState().phase).toBe('failed')
expect(usePlanStore.getState().error?.code).toBe('PD-ENV-002')
})
it('subscribes to progress before the command runs, and unsubscribes after', async () => {
// Order matters: subscribing after `uninstall_execute` starts drops the first steps into
// nothing, and the console drawer opens on a run that is already part-way through.
const order: string[] = []
const unlisten = vi.fn()
vi.mocked(ipc.onPlanProgress).mockImplementation(() => {
order.push('subscribe')
return Promise.resolve(unlisten)
})
vi.mocked(ipc.uninstallGuard).mockResolvedValue(CLEAR)
vi.mocked(ipc.uninstallExecute).mockImplementation(() => {
order.push('execute')
// A `PdError` is a plain object on the wire, not an `Error` — which is exactly why the
// stores ask `isPdError` rather than instanceof.
// eslint-disable-next-line @typescript-eslint/prefer-promise-reject-errors
return Promise.reject({ code: 'PD-PRM-002', message: 'file locked' })
})
await usePlanStore.getState().startUninstall(ENV, ['numpy'])
await usePlanStore.getState().confirmUninstall(false)
expect(order).toEqual(['subscribe', 'execute'])
// Even on failure: the summary still arrives, and a subscription left behind would double
// every line of the next run.
expect(unlisten).toHaveBeenCalledOnce()
expect(usePlanStore.getState().phase).toBe('summary')
})
})
+72
View File
@@ -0,0 +1,72 @@
/**
* The `@/ipc` mock, as TESTING §2 asks for: "IPC mocked at the typed wrapper layer".
*
* A **factory each test file passes to its own `vi.mock`**, not a module that registers the mock
* as a side effect. `vi.mock` is hoisted to the top of the file being transformed and only that
* file, so a side-effecting module would work or not depending on where the lint's import sort put
* it — correctness by luck. Each file writes one line:
*
* ```ts
* vi.mock('@/ipc', async () => {
* const { ipcMock } = await import('@/test/ipc')
* return ipcMock()
* })
* ```
*
* The factory imports lazily because the hoist puts `vi.mock` above every import in the file, so a
* top-level reference to `ipcMock` is read before it is initialized.
*
* `importOriginal` is deliberately **not** used, and that is a trade: `isPdError` has to be real,
* because both stores route every rejection through it, so it is re-exported here as the genuine
* predicate rather than a stub. Everything else is a spy. Pulling the real module in instead would
* drag `@tauri-apps/api` into jsdom, where `invoke` has no host to talk to.
*/
import { vi } from 'vitest'
/** The wrappers a test can drive. Add one when a test needs it, not before. */
export interface IpcMock {
pkgList: ReturnType<typeof vi.fn>
pkgOutdated: ReturnType<typeof vi.fn>
pinList: ReturnType<typeof vi.fn>
pinAdd: ReturnType<typeof vi.fn>
pinRemove: ReturnType<typeof vi.fn>
planResolve: ReturnType<typeof vi.fn>
planDecide: ReturnType<typeof vi.fn>
planExecute: ReturnType<typeof vi.fn>
planCancel: ReturnType<typeof vi.fn>
uninstallGuard: ReturnType<typeof vi.fn>
uninstallExecute: ReturnType<typeof vi.fn>
onPlanProgress: ReturnType<typeof vi.fn>
envScan: ReturnType<typeof vi.fn>
isPdError: (value: unknown) => boolean
}
/**
* Build the module object. Call it inside `vi.mock('@/ipc', () => ipcMock())`.
*
* Every command resolves to `undefined` unless the test says otherwise, which is what makes a test
* that forgot to script one fail on the assertion rather than on a rejection from somewhere else.
*/
export function ipcMock(): IpcMock {
return {
pkgList: vi.fn().mockResolvedValue([]),
pkgOutdated: vi.fn().mockResolvedValue([]),
pinList: vi.fn().mockResolvedValue([]),
pinAdd: vi.fn().mockResolvedValue(undefined),
pinRemove: vi.fn().mockResolvedValue(true),
planResolve: vi.fn(),
planDecide: vi.fn(),
planExecute: vi.fn(),
planCancel: vi.fn().mockResolvedValue(true),
uninstallGuard: vi.fn(),
uninstallExecute: vi.fn(),
// Returns the unlisten function the store stores and calls in its `finally`.
onPlanProgress: vi.fn().mockResolvedValue(() => undefined),
envScan: vi.fn().mockResolvedValue([]),
// Real, not a spy: the stores decide whether a rejection carries a catalog code by asking it,
// and a stub that always answered one way would make every error test agree with itself.
isPdError: (value: unknown): boolean =>
typeof value === 'object' && value !== null && 'code' in value && 'message' in value,
}
}
+21
View File
@@ -58,4 +58,25 @@ Element.prototype.getBoundingClientRect = function getBoundingClientRect(): DOMR
}
}
/**
* Give jsdom a `<dialog>`.
*
* jsdom parses the element but implements none of its behaviour: `showModal` and `close` are
* simply absent, so `PdDialog`'s mount effect throws and every test of it fails on the same line.
*
* These stubs only track `open`. **The modality is therefore not under test** — the top layer, the
* inert backdrop and native focus containment are the browser's, and jsdom has none of them. What
* these tests do cover is the policy layered on top: which control is focused, which is rendered
* first, and what each one calls. The rest belongs to the manual pass.
*/
if (typeof HTMLDialogElement !== 'undefined') {
const proto = HTMLDialogElement.prototype as unknown as Record<string, unknown>
proto['showModal'] ??= function showModal(this: HTMLDialogElement) {
this.open = true
}
proto['close'] ??= function close(this: HTMLDialogElement) {
this.open = false
}
}
export { VIEWPORT }
+23
View File
@@ -0,0 +1,23 @@
/**
* Reset a zustand store between tests.
*
* The stores are module singletons created at import time, so without this the second test in a
* file inherits whatever the first left behind — and the failure that produces is the worst kind:
* it passes alone and fails in a suite, or the reverse, depending on file order.
*
* The initial state is captured on first call, which has to happen before anything mutates the
* store. Calling it from a `beforeEach` does that by construction.
*/
const initial = new WeakMap<object, unknown>()
interface ResettableStore<T> {
getState: () => T
setState: (state: T, replace: true) => void
}
export function resetStore<T extends object>(store: ResettableStore<T>): void {
if (!initial.has(store)) initial.set(store, { ...store.getState() })
// `replace: true`, so a field a test added is removed rather than merged over.
store.setState(initial.get(store) as T, true)
}