How to get Jasmine's spyOnProperty to work?

前端 未结 2 1190
Happy的楠姐
Happy的楠姐 2020-12-17 10:17

I saw this post post and was excited to try it out, but I\'m unable to get it working. Trying to keep this simple just to figure out what\'s wrong, but even this is failing.

相关标签:
2条回答
  • 2020-12-17 10:53

    Well I spent way more time on this then I care to admit, but the answer ended up being a simple syntactical error:

    The correct value to use as the 3rd parameter is get, not getter as I had been. For example:

    spyOnProperty(someService, 'myValue', 'get').and.returnValue(false)
    

    Which I did try early on, but did not work at the time. I'm not sure what changed. I also updated @types/jasmine, along with everything else in my dev library to @latest, but I didn't restart the IDE afterward because I didn't think it'd matter. I can only guess that's why it works now.

    0 讨论(0)
  • 2020-12-17 10:58

    I was still struggling a bit to get the set to work.

    const foo = {
      get value() {},
      set value(v) {}
    };
    
    it('can spy on getters', () => {
      spyOnProperty(foo, 'value', 'get').and.returnValue(1);
      expect(foo.value).toBe(1);
    });
    
    it('and on setters', () => {
      const spiez = spyOnProperty(foo, 'value', 'set');
      foo.value = true;
      expect(spiez).toHaveBeenCalled();
    });
    
    0 讨论(0)
提交回复
热议问题