123import { beforeEach, describe, expect, it, vi } from "vitest";45import { fillFields } from "./fill";67describe("content fill", () => {8 beforeEach(() => {9 document.body.innerHTML = "";10 });1112 function makeVisibleInput(type: string): HTMLInputElement {13 const input = document.createElement("input");14 input.type = type;15 Object.defineProperty(input, "getBoundingClientRect", {16 configurable: true,17 value: () => ({18 width: 100,19 height: 20,20 top: 0,21 left: 0,22 right: 100,23 bottom: 20,24 x: 0,25 y: 0,26 toJSON: () => ({}),27 }),28 });29 document.body.appendChild(input);30 return input;31 }3233 it("fillFields writes username and password into matching inputs", () => {34 const username = makeVisibleInput("text");35 const password = makeVisibleInput("password");3637 fillFields(username, password, "june", "hunter2");3839 expect(username.value).toBe("june");40 expect(password.value).toBe("hunter2");41 });4243 it("fillFields refuses to fill when the form action domain does not match", () => {44 const form = document.createElement("form");45 form.action = "https://evil.com/login";46 const username = makeVisibleInput("text");47 const password = makeVisibleInput("password");48 form.append(username, password);49 document.body.appendChild(form);5051 fillFields(username, password, "june", "hunter2", form, "github.com");5253 expect(username.value).toBe("");54 expect(password.value).toBe("");55 });5657 it("fillFields still fills the username when the username field is hidden", () => {58 const username = makeVisibleInput("text");59 const password = makeVisibleInput("password");60 Object.defineProperty(username, "getBoundingClientRect", {61 value: () => ({62 width: 0,63 height: 0,64 top: 0,65 left: 0,66 right: 0,67 bottom: 0,68 x: 0,69 y: 0,70 toJSON: () => ({}),71 }),72 });7374 fillFields(username, password, "june", "hunter2");7576 expect(username.value).toBe("june");77 expect(password.value).toBe("hunter2");78 });7980 it("fillFields dispatches standard input/change events rather than custom password events", () => {81 const username = makeVisibleInput("text");82 const password = makeVisibleInput("password");83 const usernameDispatch = vi.spyOn(username, "dispatchEvent");84 const passwordDispatch = vi.spyOn(password, "dispatchEvent");8586 fillFields(username, password, "june", "hunter2");8788 expect(usernameDispatch.mock.calls.map(([event]) => event.type)).toEqual(["input", "change"]);89 expect(passwordDispatch.mock.calls.map(([event]) => event.type)).toEqual(["input", "change"]);90 expect(passwordDispatch.mock.calls.every(([event]) => !(event instanceof CustomEvent))).toBe(true);91 });92});