import { describe, expect, test } from "bun:test";
import { fireEvent, screen, waitFor } from "@testing-library/react";
import type { Esquemas } from "../../../api/cliente";
{%- if fill_helpers %}
import { {{ fill_helpers | join(sep=", ") }} } from "../../../compartido/formularios";
{%- endif %}
import { apiFalsa } from "../../../pruebas/api-falsa";
{%- if access.get_roles %}
import { MadreUsuarioActual } from "../../../pruebas/auth";
{%- endif %}
{%- for t in seeded_targets %}
import { coleccion{{ t.pascal }}, Madre{{ t.pascal }} } from "../../../pruebas/{{ t.kebab }}";
{%- endfor %}
import { coleccion{{ pascal }}, Madre{{ pascal }} } from "../../../pruebas/{{ kebab }}";
import { renderizarPantalla } from "../../../pruebas/renderizar";
import { aProblema } from "../mensajes";
import { ContenedorFormulario{{ pascal }} } from "./formulario-{{ kebab }}";
function escribir(etiqueta: string, valor: string) {
fireEvent.change(screen.getByLabelText(etiqueta), { target: { value: valor } });
}
{%- if selects %}
/** Elige `id` en el select de una referencia, en cuanto se cargan sus objetivos. */
async function elegir(etiqueta: string, id: string) {
const select = screen.getByLabelText(etiqueta);
await waitFor(() => expect(select.querySelector(`option[value="${id}"]`)).not.toBeNull());
fireEvent.change(select, { target: { value: id } });
}
{%- endif %}
{%- if seeded_targets %}
/** Las colecciones que leen los selects, con lo que referencia `dueno`. */
function referenciadosPor(dueno: Partial<Esquemas["Dto{{ pascal }}"]>) {
{%- if referenced_inline %}
return [{% for t in seeded_targets %}coleccion{{ t.pascal }}([{{ t.seeds | join(sep=", ") }}]){% if not loop.last %}, {% endif %}{% endfor %}];
{%- else %}
return [
{%- for t in seeded_targets %}
{%- if t.seeds_inline %}
coleccion{{ t.pascal }}([{{ t.seeds | join(sep=", ") }}]),
{%- else %}
coleccion{{ t.pascal }}([
{%- for seed in t.seeds %}
{{ seed }},
{%- endfor %}
]),
{%- endif %}
{%- endfor %}
];
{%- endif %}
}
{%- endif %}
/** Rellena el formulario vacío con `peticion`, como lo haría quien lo usa. */
async function rellenar(peticion: Esquemas["PeticionCrear{{ pascal }}"]) {
await screen.findByText("Guardar");
{%- for f in create_fields %}
{%- if f.is_composite %}
{%- for p in f.parts %}
{%- if p.input == "checkbox" %}
if ({{ p.request_to_form }}) fireEvent.click(screen.getByLabelText("{{ p.label }}"));
{%- else %}
escribir("{{ p.label }}", {{ p.request_to_form }});
{%- endif %}
{%- endfor %}
{%- elif f.input == "checkbox" %}
if (peticion.{{ f.camel }}) fireEvent.click(screen.getByLabelText("{{ f.label }}"));
{%- elif f.input == "reference" %}
await elegir("{{ f.label }}", {{ f.request_to_form }});
{%- elif f.input == "references" %}
{%- else %}
escribir("{{ f.label }}", {{ f.request_to_form }});
{%- endif %}
{%- endfor %}
}
describe("ContenedorFormulario{{ pascal }}", () => {
test("debería crear con lo escrito e ir a su detalle", async () => {
// Preparar
const peticion = Madre{{ pascal }}.peticion();
const guardados = coleccion{{ pascal }}();
const api = apiFalsa([guardados{% if seeded_targets %}, ...referenciadosPor(peticion){% endif %}]);
const pantalla = <ContenedorFormulario{{ pascal }} />;
const { historial } = renderizarPantalla(pantalla, { api });
await rellenar(peticion);
// Actuar
fireEvent.click(screen.getByText("Guardar"));
// Comprobar
await waitFor(() => expect(historial.at(-1)).toStartWith("/{{ plural }}/"));
const [creado] = guardados.elementos.values();
expect(creado).toMatchObject(peticion);
expect(historial.at(-1)).toBe(`/{{ plural }}/${creado?.id}`);
});
{%- if access.get_roles %}
test("debería ir {% if access.list_roles %}al panel{% else %}a la lista{% endif %} tras crear cuando no puede ver lo creado", async () => {
// Preparar
const peticion = Madre{{ pascal }}.peticion();
const api = apiFalsa([coleccion{{ pascal }}(){% if seeded_targets %}, ...referenciadosPor(peticion){% endif %}]);
const pantalla = <ContenedorFormulario{{ pascal }} />;
const usuario = MadreUsuarioActual.aleatorio();
const { historial } = renderizarPantalla(pantalla, { api }, "/", { usuario });
await rellenar(peticion);
// Actuar
fireEvent.click(screen.getByText("Guardar"));
// Comprobar
await waitFor(() => expect(historial.at(-1)).toBe("{% if access.list_roles %}/?guardado{% else %}/{{ plural }}{% endif %}"));
});
{%- endif %}
{%- for s in sets %}
test("debería mandar en {{ s.label }} las casillas marcadas", async () => {
// Preparar: dos {{ s.target_pascal }} que elegir.
const peticion = Madre{{ pascal }}.peticion();
const [primero, segundo] = [crypto.randomUUID(), crypto.randomUUID()];
const guardados = coleccion{{ pascal }}();
const referenciados = referenciadosPor({ ...peticion, {{ s.camel }}: [primero, segundo] });
const api = apiFalsa([guardados, ...referenciados]);
renderizarPantalla(<ContenedorFormulario{{ pascal }} />, { api });
await rellenar(peticion);
// Las casillas, por su id: el objetivo de otra referencia también es una opción.
const grupo = screen.getByRole("group", { name: "{{ s.label }}" });
const casilla = (id: string) => grupo.querySelector(`input[value="${id}"]`);
await waitFor(() => expect(casilla(segundo)).not.toBeNull());
// Actuar: marca las dos y desmarca la primera.
for (const id of [primero, segundo, primero]) {
const marcada = casilla(id);
if (marcada) fireEvent.click(marcada);
}
fireEvent.click(screen.getByText("Guardar"));
// Comprobar
await waitFor(() => expect(guardados.elementos.size).toBe(1));
const [creado] = guardados.elementos.values();
expect(creado?.{{ s.camel }}).toEqual([segundo]);
});
{%- endfor %}
{%- for f in create_fields %}{% if f.is_enum and f.required %}
test("debería traer elegida la primera variante de {{ f.label }}", async () => {
// Preparar
const api = apiFalsa([coleccion{{ pascal }}()]);
// Actuar
renderizarPantalla(<ContenedorFormulario{{ pascal }} />, { api });
// Comprobar
await screen.findByText("Guardar");
const select = screen.getByLabelText("{{ f.label }}") as HTMLSelectElement;
expect(select.value).toBe("{{ f.options.0.value }}");
});
{%- endif %}{% endfor %}
test("debería guardar la edición cuando se envía el formulario", async () => {
// Preparar
const sembrado = Madre{{ pascal }}.aleatorio();
const guardados = coleccion{{ pascal }}([sembrado]);
const api = apiFalsa([guardados{% if seeded_targets %}, ...referenciadosPor(sembrado){% endif %}]);
const pantalla = <ContenedorFormulario{{ pascal }} id={sembrado.id} />;
const { historial } = renderizarPantalla(pantalla, { api });
{%- set required_refs = fields | filter(attribute="input", value="reference") | filter(attribute="required", value=true) %}
{%- if required_refs %}
// Un select obligatorio sin la opción de lo que referencia no deja enviar el formulario.
await screen.findByText("Guardar");
{%- for f in required_refs %}
await elegir("{{ f.label }}", sembrado.{{ f.camel }});
{%- endfor %}
// Actuar
fireEvent.click(screen.getByText("Guardar"));
{%- else %}
// Actuar
fireEvent.click(await screen.findByText("Guardar"));
{%- endif %}
// Comprobar
await waitFor(() => expect(historial.at(-1)).toBe(`/{{ plural }}/${sembrado.id}`));
expect(guardados.elementos.get(sembrado.id)).toEqual(sembrado);
});
test("debería mostrar el propio código cuando la API responde uno que el formulario no conoce", async () => {
// Preparar
const peticion = Madre{{ pascal }}.peticion();
const codigo = "{{ snake }}.validacion.invalido";
const fallos = { "POST /{{ plural }}": codigo };
const api = apiFalsa([coleccion{{ pascal }}(){% if seeded_targets %}, ...referenciadosPor(peticion){% endif %}], fallos);
renderizarPantalla(<ContenedorFormulario{{ pascal }} />, { api });
await rellenar(peticion);
// Actuar
fireEvent.click(screen.getByText("Guardar"));
// Comprobar
expect((await screen.findByRole("alert")).textContent).toBe(codigo);
});
{%- if duplicate.field %}
test("debería decir bajo su input que {{ duplicate.label }} ya está en uso cuando la API responde un duplicado", async () => {
// Preparar
const peticion = Madre{{ pascal }}.peticion();
const codigo = "{{ snake }}.duplicado";
const fallos = { "POST /{{ plural }}": codigo };
const api = apiFalsa([coleccion{{ pascal }}(){% if seeded_targets %}, ...referenciadosPor(peticion){% endif %}], fallos);
renderizarPantalla(<ContenedorFormulario{{ pascal }} />, { api });
await rellenar(peticion);
// Actuar
fireEvent.click(screen.getByText("Guardar"));
// Comprobar
expect(await screen.findByText(aProblema(codigo).texto)).toBeTruthy();
const campo = screen.getByLabelText("{{ duplicate.label }}");
expect(campo.getAttribute("aria-invalid")).toBe("true");
expect(screen.queryByRole("alert")).toBeNull();
});
{%- else %}
test("debería decir que los valores ya están en uso cuando la API responde un duplicado", async () => {
// Preparar
const peticion = Madre{{ pascal }}.peticion();
const codigo = "{{ snake }}.duplicado";
const fallos = { "POST /{{ plural }}": codigo };
const api = apiFalsa([coleccion{{ pascal }}(){% if seeded_targets %}, ...referenciadosPor(peticion){% endif %}], fallos);
renderizarPantalla(<ContenedorFormulario{{ pascal }} />, { api });
await rellenar(peticion);
// Actuar
fireEvent.click(screen.getByText("Guardar"));
// Comprobar
expect((await screen.findByRole("alert")).textContent).toBe(aProblema(codigo).texto);
});
{%- endif %}
{%- for t in targets %}{% if t.selects > 0 %}
test("debería ofrecer cada {{ t.words }} en sus selects", async () => {
// Preparar
const {{ t.ident }} = Madre{{ t.pascal }}.aleatorio();
const api = apiFalsa([coleccion{{ t.pascal }}([{{ t.ident }}])]);
// Actuar
renderizarPantalla(<ContenedorFormulario{{ pascal }} />, { api });
// Comprobar
{%- if t.option_test_inline %}
const opciones = await screen.findAllByRole("option", { name: {{ t.label_of }} });
{%- else %}
const opciones = await screen.findAllByRole("option", {
name: {{ t.label_of }},
});
{%- endif %}
expect(opciones).toHaveLength({{ t.selects }});
});
{%- endif %}{% endfor %}
{%- for r in references | filter(attribute="is_self", value=true) %}
test("debería quitar de {{ r.label }} lo que se edita", async () => {
// Preparar: una autorreferencia no apunta a su propia fila.
const objetivo = Madre{{ pascal }}.aleatorio();
const sembrado = Madre{{ pascal }}.aleatorio();
const api = apiFalsa([coleccion{{ pascal }}([sembrado, objetivo]){% if seeded_targets %}, ...referenciadosPor(sembrado){% endif %}]);
// Actuar
renderizarPantalla(<ContenedorFormulario{{ pascal }} id={sembrado.id} />, { api });
// Comprobar
{%- if r.is_set %}
const select = await screen.findByRole("group", { name: "{{ r.label }}" });
const selector = `input[value="${objetivo.id}"]`;
await waitFor(() => expect(select.querySelector(selector)).not.toBeNull());
expect(select.querySelector(`input[value="${sembrado.id}"]`)).toBeNull();
{%- else %}
const select = await screen.findByLabelText("{{ r.label }}");
const selector = `option[value="${objetivo.id}"]`;
await waitFor(() => expect(select.querySelector(selector)).not.toBeNull());
expect(select.querySelector(`option[value="${sembrado.id}"]`)).toBeNull();
{%- endif %}
});
{%- endfor %}
{%- if field_problem %}
test("debería mostrar el mensaje bajo su input cuando la API rechaza un campo", async () => {
// Preparar
const peticion = Madre{{ pascal }}.peticion();
const codigo = "{{ field_problem.code }}";
const fallos = { "POST /{{ plural }}": codigo };
const api = apiFalsa([coleccion{{ pascal }}(){% if seeded_targets %}, ...referenciadosPor(peticion){% endif %}], fallos);
renderizarPantalla(<ContenedorFormulario{{ pascal }} />, { api });
await rellenar(peticion);
// Actuar
fireEvent.click(screen.getByText("Guardar"));
// Comprobar
expect(await screen.findByText(aProblema(codigo).texto)).toBeTruthy();
const campo = screen.getByLabelText("{{ field_problem.label }}");
expect(campo.getAttribute("aria-invalid")).toBe("true");
expect(screen.queryByRole("alert")).toBeNull();
});
{%- endif %}
{%- for r in references | filter(attribute="required", value=true) %}{% if loop.first %}
test("debería dejar elegido {{ r.label }} cuando la URL lo trae", async () => {
// Preparar: «Comprar» desde {{ r.label }} lleva a `/{{ plural }}/nuevo?{{ r.camel }}=…`
const peticion = Madre{{ pascal }}.peticion();
const api = apiFalsa([coleccion{{ pascal }}(), ...referenciadosPor(peticion)]);
const ruta = `/{{ plural }}/nuevo?{{ r.camel }}=${peticion.{{ r.camel }}}`;
// Actuar
renderizarPantalla(<ContenedorFormulario{{ pascal }} />, { api }, ruta);
// Comprobar
const select = (await screen.findByLabelText("{{ r.label }}")) as HTMLSelectElement;
await waitFor(() => expect(select.value).toBe(peticion.{{ r.camel }}));
});
{%- endif %}{% endfor %}
});