How to spyOn a value property (rather than a method) with Jasmine

前端 未结 10 2231
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-01 04:12

Jasmine\'s spyOn is good to change a method\'s behavior, but is there any way to change a value property (rather than a method) for an object? the code could be

10条回答
  •  情歌与酒
    2020-12-01 04:29

    If you are using ES6 (Babel) or TypeScript you can stub out the property using get and set accessors

    export class SomeClassStub {
      getValueA = jasmine.createSpy('getValueA');
      setValueA = jasmine.createSpy('setValueA');
      get valueA() { return this.getValueA(); }
      set valueA(value) { this.setValueA(value); }
    }
    

    Then in your test you can check that the property is set with:

    stub.valueA = 'foo';
    
    expect(stub.setValueA).toHaveBeenCalledWith('foo');
    

提交回复
热议问题