|
| 1 | +import { describe, it, expect, beforeEach } from "vitest" |
| 2 | +import { focusFirstError } from "./focus-first-error.ts" |
| 3 | + |
| 4 | +describe("focusFirstError", () => { |
| 5 | + beforeEach(() => { |
| 6 | + document.body.innerHTML = "" |
| 7 | + }) |
| 8 | + |
| 9 | + it("focuses the field carrying the generated id", () => { |
| 10 | + document.body.innerHTML = `<input id="root_name" />` |
| 11 | + const field = document.getElementById("root_name") |
| 12 | + |
| 13 | + focusFirstError({ property: ".name" }) |
| 14 | + |
| 15 | + expect(document.activeElement).toBe(field) |
| 16 | + }) |
| 17 | + |
| 18 | + it("resolves a bracketed property path", () => { |
| 19 | + document.body.innerHTML = `<input id="root_spec_first-name" />` |
| 20 | + const field = document.getElementById("root_spec_first-name") |
| 21 | + |
| 22 | + focusFirstError({ property: ".spec['first-name']" }) |
| 23 | + |
| 24 | + expect(document.activeElement).toBe(field) |
| 25 | + }) |
| 26 | + |
| 27 | + // SourceField and SourceWidget render no element carrying the generated id, |
| 28 | + // only radios named `<id>-source`, so the exact lookup misses and a blocked |
| 29 | + // submit used to scroll nowhere. |
| 30 | + it("falls back to the name attribute when no element carries the id", () => { |
| 31 | + document.body.innerHTML = ` |
| 32 | + <div class="field"> |
| 33 | + <input type="radio" name="root_source-source" value="http" /> |
| 34 | + <input type="radio" name="root_source-source" value="pvc" /> |
| 35 | + </div> |
| 36 | + ` |
| 37 | + const first = document.querySelector<HTMLInputElement>('input[value="http"]') |
| 38 | + |
| 39 | + focusFirstError({ property: ".source" }) |
| 40 | + |
| 41 | + expect(document.getElementById("root_source")).toBeNull() |
| 42 | + expect(document.activeElement).toBe(first) |
| 43 | + }) |
| 44 | + |
| 45 | + it("does nothing when the field is nowhere in the document", () => { |
| 46 | + document.body.innerHTML = `<input id="root_other" />` |
| 47 | + |
| 48 | + expect(() => focusFirstError({ property: ".missing" })).not.toThrow() |
| 49 | + expect(document.activeElement).toBe(document.body) |
| 50 | + }) |
| 51 | +}) |
0 commit comments