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";
{%- for t in 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 { ContenedorFormulario{{ pascal }} } from "./formulario-{{ kebab }}";
function escribir(etiqueta: string, valor: string) {
fireEvent.change(screen.getByLabelText(etiqueta), { target: { value: valor } });
}
{%- if targets %}
/** 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 } });
}
/** 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 targets %}coleccion{{ t.pascal }}([{{ t.seeds | join(sep=", ") }}]){% if not loop.last %}, {% endif %}{% endfor %}];
{%- else %}
return [
{%- for t in 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 fields %}
{%- if 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 }});
{%- 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 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}`);
});
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 targets %}, ...referenciadosPor(sembrado){% endif %}]);
const pantalla = <ContenedorFormulario{{ pascal }} id={sembrado.id} />;
const { historial } = renderizarPantalla(pantalla, { api });
// Actuar
fireEvent.click(await screen.findByText("Guardar"));
// 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 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);
});
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 fallos = { "POST /{{ plural }}": "{{ snake }}.duplicado" };
const api = apiFalsa([coleccion{{ pascal }}(){% if 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("{{ duplicate_text }}");
});
{%- for t in targets %}
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
const opciones = await screen.findAllByRole("option", { name: {{ t.ident }}.{{ t.label }} });
expect(opciones).toHaveLength({{ t.fields | length }});
});
{%- 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 fallos = { "POST /{{ plural }}": "{{ field_problem.code }}" };
const api = apiFalsa([coleccion{{ pascal }}(){% if targets %}, ...referenciadosPor(peticion){% endif %}], fallos);
renderizarPantalla(<ContenedorFormulario{{ pascal }} />, { api });
await rellenar(peticion);
// Actuar
fireEvent.click(screen.getByText("Guardar"));
// Comprobar
expect(await screen.findByText("{{ field_problem.text }}")).toBeTruthy();
const campo = screen.getByLabelText("{{ field_problem.label }}");
expect(campo.getAttribute("aria-invalid")).toBe("true");
expect(screen.queryByRole("alert")).toBeNull();
});
{%- endif %}
});