How can I spy on a getter property using jasmine?

前端 未结 6 1863
南笙
南笙 2020-12-14 06:02

How can I spy on a getter property using jasmine?

var o = { get foo() {}, };

spyOn(o, \'foo\').and.returnValue(\'bar\'); // Doesn\'t work.

6条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-14 06:17

    I don't believe you can spy on getters. The point of a getter is that it acts exactly like a property, so how would jasmine be able to spy on it when it is never called like a function but rather is accessed like a property.

    As a workaround, you could have your getter call another function and spy on that instead.

    var o = {
         _foo: function(){
            return 'foo'; 
         }, 
         get foo(){
            return this._foo();
         }
    };
    
    spyOn(o, '_foo').and.returnValue('bar'); 
    

提交回复
热议问题