Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

185
Views
Simule solo una función del módulo pero deje el resto con la funcionalidad original

Solo quiero simular una sola función (llamada exportación) de un módulo, pero dejar intactas el resto de las funciones del módulo.

Usar jest.mock('package-name') hace que todas las funciones exportadas se simulan, lo cual no quiero.

Intenté distribuir las exportaciones nombradas de nuevo en el objeto simulado...

 import * as utils from './utilities.js'; jest.mock(utils, () => ({ ...utils speak: jest.fn(), }));

pero obtuve este error:

La fábrica de módulos de jest.mock() no puede hacer referencia a ninguna variable fuera del alcance.

over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

Lo más destacado de esta respuesta es jest.requireActual() , esta es una utilidad muy útil que dice en broma que "Oye, mantén intactas todas las funcionalidades originales e impórtalas".

 jest.mock('./utilities.js', () => ({ ...jest.requireActual('./utilities.js'), speak: jest.fn(), }));

Tomemos otro escenario común, estás usando la enzima ShallowWrapper y no funciona bien con el gancho useContext(), entonces, ¿qué vas a hacer? Si bien estoy seguro de que hay varias formas, pero esta es la que me gusta:

 import React from "react"; jest.mock("react", () => ({ ...jest.requireActual("react"), // import and retain the original functionalities useContext: jest.fn().mockReturnValue({foo: 'bar'}) // overwrite useContext }))

La ventaja de hacerlo de esta manera es que aún puede usar import React, { useContext } from "react" en su código original sin preocuparse por convertirlos en React.useContext() como lo haría si estuviera usando jest.spyOn( Reaccionar, 'usarContexto')

over 4 years ago · Santiago Trujillo Report

0

La forma más sencilla es usar jest.spyOn y luego .mockImplementation() . Esto permitirá que todas las demás funciones en el módulo continúen funcionando como están definidas.

Para paquetes:

 import axios from 'axios'; jest.spyOn(axios, 'get'); axios.get.mockImplementation(() => { /* do thing */ });

Para módulos con exportaciones con nombre:

 import * as utils from './utilities.js'; jest.spyOn(utils, 'speak'); utils.speak.mockImplementation(() => { /* do thing */ });

Documentos aquí: https://jestjs.io/docs/en/jest-object#jestspyonobject-methodname

over 4 years ago · Santiago Trujillo Report

0

Para mí esto funcionó:

 const utils = require('./utilities.js'); ... jest.spyOn(utils, 'speak').mockImplementation(() => jest.fn());
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!