1+ import { describe , it , expect , vi , beforeEach } from 'vitest'
2+ import { render , screen } from '@testing-library/svelte'
3+ import Counter from './+page.svelte'
4+ import userEvent from '@testing-library/user-event'
5+
6+ describe ( 'count letters' , ( ) => {
7+ beforeEach ( ( ) => {
8+ vi . clearAllMocks ( )
9+ } )
10+
11+ it ( 'should start with empty string and should show no result' , ( ) => {
12+ render ( Counter )
13+
14+ const text = screen . getByTestId ( 'palabra' ) as HTMLInputElement
15+ expect ( text . value ) . to . equal ( '' )
16+ expect ( screen . queryByTestId ( 'resultado' ) ) . not . toBeTruthy ( )
17+ } )
18+
19+ it ( 'should show the word length when a word is passed as props' , async ( ) => {
20+ render ( Counter , {
21+ props : {
22+ form : {
23+ palabra : 'hola' ,
24+ longitud : 4
25+ }
26+ }
27+ } )
28+ const palabra = await screen . getByTestId ( 'palabra' ) as HTMLInputElement
29+ expect ( palabra . value ) . to . equal ( '' )
30+ expect ( screen . getByTestId ( 'resultado' ) . textContent ) . to . equal ( 'La palabra "hola" tiene 4 letras.' )
31+ } )
32+
33+ it ( 'should navigate to the home page when link is clicked' , async ( ) => {
34+ render ( Counter )
35+ const backLink = screen . getByTestId ( 'back-link' ) as HTMLAnchorElement
36+ await userEvent . click ( backLink )
37+ expect ( window . location . pathname ) . toBe ( '/' )
38+ } )
39+
40+ it ( 'envía la palabra correctamente al hacer submit' , async ( ) => {
41+ const mockFetch = vi . fn ( ) . mockResolvedValue ( {
42+ ok : true ,
43+ json : async ( ) => ( {
44+ type : 'success' ,
45+ data : { palabra : 'hola' , longitud : 4 }
46+ } )
47+ } )
48+
49+ globalThis . fetch = mockFetch
50+
51+ render ( Counter , { props : { form : null } } )
52+
53+ const input = screen . getByTestId ( 'palabra' )
54+ const submit = screen . getByTestId ( 'submit' )
55+
56+ await userEvent . type ( input , 'hola' )
57+ await userEvent . click ( submit )
58+
59+ // Verificar que se llamó fetch
60+ expect ( mockFetch ) . toHaveBeenCalled ( )
61+
62+ // Verificamos el FormData enviado
63+ const fetchCall = mockFetch . mock . calls [ 0 ]
64+ const requestInit = fetchCall [ 1 ] as RequestInit
65+ expect ( requestInit . body ) . toBeInstanceOf ( URLSearchParams )
66+ const params = new URLSearchParams ( requestInit . body as string )
67+ expect ( params . get ( 'palabra' ) ) . toBe ( 'hola' )
68+ } )
69+
70+
71+ } )
0 commit comments