How to mock / replace an object getter function using 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 will not replace getter

"cannot set get value"

+9
source share
3 answers

you can use Object.defineProperty

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

For everyone who came across this answer, in Jest 22.1.0 there was an opportunity to spy on receiving and installation methods .

Edit: scieslak , getter setter, Jest mocks , :

class MyClass {
  get something() {
    return 'foo'
  }
}

jest.spyOn(MyClass, 'something', 'get').mockReturnValue('bar')
const something = new MyClass().something

expect(something).toEqual('bar')
+12

OMG I've been here so many times. Finally, find the right solution for this. If you care only about espionage. Go to @Franey's answer. However, if you really need to specify a value for the recipient, 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)
  })
})
+2
source

Source: https://habr.com/ru/post/1675989/


All Articles