javascriptreactjsmockingsinonjestjs

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


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"


Solution

  • You could use Object.defineProperty

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