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

前端 未结 3 1275
小鲜肉
小鲜肉 2021-02-03 17:44

In Sinon I can do the following:

var myObj = {
    prop: \'foo\'
};

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

myObj.prop; /         


        
3条回答
  •  礼貌的吻别
    2021-02-03 18:38

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

提交回复
热议问题