Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

412
Vistas
¿Cómo simular el valor devuelto del gancho personalizado de reacción?

Aquí está mi gancho personalizado:

 export function useClientRect() { const [scrollH, setScrollH] = useState(0); const [clientH, setClientH] = useState(0); const ref = useCallback(node => { if (node !== null) { setScrollH(node.scrollHeight); setClientH(node.clientHeight); } }, []); return [scrollH, clientH, ref]; } }

Quiero que cada vez que se llame, devuelva mis valores. me gusta:

 jest.mock('useClientRect', () => [300, 200, () => {}]);

¿Cómo puedo conseguir esto?

over 4 years ago · Santiago Trujillo
3 Respuestas
Responde la pregunta

0

Cargue el gancho como un módulo. Luego simula el módulo:

 jest.mock('module_name', () => ({ useClientRect: () => [300, 200, jest.fn()] }));

mock debe llamarse encima del archivo fuera de test fn. Por lo tanto, vamos a tener solo una matriz como valor simulado.

Si quieres simular el anzuelo con diferentes valores en diferentes pruebas:

 import * as hooks from 'module_name'; it('a test', () => { jest.spyOn(hooks, 'useClientRect').mockImplementation(() => ([100, 200, jest.fn()])); //rest of the test });
over 4 years ago · Santiago Trujillo Denunciar

0

Bueno, esto es bastante complicado y, a veces, los desarrolladores se confunden con la biblioteca, pero una vez que te acostumbras, se vuelve pan comido. Me enfrenté a un problema similar hace unas horas y estoy compartiendo mi solución para que pueda obtener su solución fácilmente.

Mi gancho personalizado:

 import { useEffect, useState } from "react"; import { getFileData } from "../../API/gistsAPIs"; export const useFilesData = (fileUrl: string) => { const [fileData, setFileData] = useState<string>(""); const [loading, setLoading] = useState<boolean>(false); useEffect(() => { setLoading(true); getFileData(fileUrl).then((fileContent) => { setFileData(fileContent); setLoading(false); }); }, [fileUrl]); return { fileData, loading }; };

Mi código simulado: incluya este simulacro en el archivo de prueba fuera de su función de prueba. Nota: tenga cuidado con el objeto de retorno del simulacro, debe coincidir con la respuesta esperada

 const mockResponse = { fileData: "This is a mocked file", loading: false, }; jest.mock("../fileView", () => { return { useFilesData: () => { return { fileData: "This is a mocked file", loading: false, }; }, }; });

archivo de prueba completo sería:

 import { render, screen, waitFor } from "@testing-library/react"; import "@testing-library/jest-dom/extend-expect"; import FileViewer from "../FileViewer"; const mockResponse = { fileData: "This is a mocked file", loading: false, }; jest.mock("../fileView", () => { return { useFilesData: () => { return { fileData: "This is a mocked file", loading: false, }; }, }; }); describe("File Viewer", () => { it("display the file heading", async () => { render(<FileViewer fileUrl="" filename="regex-tutorial.md" className="" />); const paragraphEl = await screen.findByRole("fileHeadingDiplay"); expect(paragraphEl).toHaveTextContent("regex-tutorial.md"); }); }

¡¡Salud!! y si esto es útil, sea amable con los otros desarrolladores y dele un pulgar hacia arriba.

over 4 years ago · Santiago Trujillo Denunciar

0

Agregando a esta respuesta para los usuarios de mecanografiados que se encuentran con el TS2339: Property 'mockReturnValue' does not exist on type . Ahora hay una función jest.MockedFunction a la que puede llamar para simular con Type mocked (que es un puerto de la función simulada ts-jest/utils).

 import useClientRect from './path/to/useClientRect'; jest.mock('./path/to/useClientRect'); const mockUseClientRect = useClientRect as jest.MockedFunction<typeof useClientRect> describe("useClientRect", () => { it("mocks the hook's return value", () => { mockUseClientRect.mockReturnValue([300, 200, () => {}]); // ... do stuff }); it("mocks the hook's implementation", () => { mockUseClientRect.mockImplementation(() => [300, 200, () => {}]); // ... do stuff }); });
over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda