midudev / aprendiendo-react

Curso para aprender React desde cero
https://twitch.tv/midudev
7.5k stars 1.09k forks source link

[07-midu-router] vitest mock del current path no funciona #111

Open MarcAlmirallBertran opened 4 months ago

MarcAlmirallBertran commented 4 months ago

He estado revisando los test donde se usa el getCurrentPath y no consigo que funcionen, siempre me sale el path '/'. He revisado el repo de midu y parece que ahi tampoco funciona, alguien tiene alguna idea? Este es el error que me sale usando el repo de midu, en mi caso si que funciona pero parece que no hace caso de lo que le marco en el mockReturnValueOnce() image

Joselow commented 2 months ago

@MarcAlmirallBertran He estado investigando el último test "should navigate using Links" y he encontrado un problema. En la prueba realizada por @midudev, se utilizó '/about' y aparentemente todo funcionó bien, pero en realidad no encontró esa ruta debido a un click en . El éxito aparente se debe a que en el test previo "should render the component of the first route that matches", se configuró getCurrentPath.mockReturnValue('/about'). Esto permitió que el último test funcionara correctamente con esa ruta específica.

Sin embargo, si pruebas con otras rutas, el test no funcionará correctamente. Además, si en el test anterior usas getCurrentPath.mockReturnValueOnce('/about') en lugar de getCurrentPath.mockReturnValue('/about'), el último test también fallará si estaba con el 'about'. Otro punto importante es que si cambias la ruta en el test "should render the component of the first route that matches" en lugar de poner getCurrentPath.mockReturnValue('/about') pones getCurrentPath.mockReturnValue('/newRoute') y esa nueva ruta se coloca: <Link to="/newRoute"> y en <Route path='/newRoute' component={() => <h1>New Route</h1>} /> del ultimo test, entonces funcionará correctamente, pero solo si cambiamos esa ruta en el anterior test usando getCurrentPath.mockReturnValue('/newRoute').

El problema principal radica en que al simular el click en el , el componente Router escucha el evento NAVIGATE_EVENT y llama a la función getCurrentPath, la cual está definida como: export const getCurrentPath = () => window.location.pathname En el entorno de prueba, esta función devuelve undefined porque no estamos en un navegador real. Por lo tanto, el Router renderiza el componente por defecto en lugar del componente esperado.