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

I_like_foxes picture I_like_foxes · Apr 29, 2017 · Viewed 34k times · Source

In Sinon I can do the following:

var myObj = {
    prop: 'foo'
};

sinon.stub(myObj, 'prop').get(function getterFn() {
    return 'bar';
});

myObj.prop; // 'bar'

But how can I do the same with Jest? I can't just overwrite the function with something like jest.fn(), because it won't replace the getter

"can't set the value of get"

Answer

Franey picture Franey · Mar 23, 2018

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().something

expect(something).toEqual('bar')