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

239
Views
¿Cómo simular/reemplazar la función getter del objeto con Jest?

En Sinon puedo hacer lo siguiente:

 var myObj = { prop: 'foo' }; sinon.stub(myObj, 'prop').get(function getterFn() { return 'bar'; }); myObj.prop; // 'bar'

Pero, ¿cómo puedo hacer lo mismo con Jest? No puedo simplemente sobrescribir la función con algo como jest.fn() , porque no reemplazará al getter

"no se puede establecer el valor de get"

over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

Para cualquier otra persona que se encuentre con esta respuesta, Jest 22.1.0 introdujo la capacidad deespiar los métodos getter y setter .

Editar: como en la respuesta de scieslak a continuación, debido a que puede espiar los métodos getter y setter, puede usar simulacros de Jest con ellos, al igual que con cualquier otra función:

 class MyClass { get something() { return 'foo' } } jest.spyOn(MyClass, 'something', 'get').mockReturnValue('bar') const something = new MyClass().something expect(something).toEqual('bar')
over 4 years ago · Santiago Trujillo Report

0

Podrías usar Object.defineProperty

 Object.defineProperty(myObj, 'prop', { get: jest.fn(() => 'bar'), set: jest.fn() });
over 4 years ago · Santiago Trujillo Report

0

Si solo te importa espiar, busca la respuesta de @Franey. Sin embargo, si realmente necesita agregar un valor para el getter, así es como puede hacerlo:

 class Awesomeness { get isAwesome() { return true } } describe('Awesomeness', () => { it('is not always awesome', () => { const awesomeness = new Awesomeness jest.spyOn(awesomeness, 'isAwesome', 'get').mockReturnValue(false) expect(awesomeness.isAwesome).toEqual(false) }) })
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!