How to mock/replace getter function of object with Jest? How to mock/replace getter function of object with Jest? reactjs reactjs

How to mock/replace getter function of object with Jest?


For anyone else stumbling across this answer, Jest 22.1.0 introduced the ability to spy on getter and setter methods.

Edit: like in scieslak's answer below, because you can spy on getter and setter methods, you can use Jest mocks with them, just like with any other function:

class MyClass {  get something() {    return 'foo'  }}jest.spyOn(MyClass, 'something', 'get').mockReturnValue('bar')const something = new MyClass().somethingexpect(something).toEqual('bar')


You could use Object.defineProperty

Object.defineProperty(myObj, 'prop', {  get: jest.fn(() => 'bar'),  set: jest.fn()});


OMG I've been here so many times. Finally figure out the proper solution for this.If you care about spying only. Go for @Franey 's answer. However if you actually need to stub a value for the getter this is how you can do it

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)  })})