Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
318 views
in Technique[技术] by (71.8m points)

javascript - How to get Jasmine's spyOnProperty to work?

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.

export class SomeService {
...
private _myValue: Boolean = false;
get myValue(): Boolean {
    return this._myValue;
}
set myValue(helper: Boolean) {
    this._myValue = helper;
}

And in my unit test, I have:

 it('should ', inject([SomeService], (someService: SomeService) => {         
    let oldValue = someService.myValue;    
    expect(oldValue).toBe(false); // passes, clearly we can use our getter
    someService.myValue = true;    
    expect(someService.myValue).toBe(true); // passed, clearly the setter worked

    spyOnProperty(someService, 'myValue', 'getter').and.returnValue(false); // Property myValue does not have access type getter

    //spyOnProperty(someService, 'myValue', 'get').and.returnValue(false);same error if tried this way

    expect(someService.myValue).toBe(false);
 }));

I put the values up top to clearly show I can get and set the value. That has no problems. Wallaby shows ReferenceError: spyOnProperty is not defined on the spyOnProperty line. I'm not sure if that helps, but the errors I put above were what karma gives me when I run those tests.

Anyone who has gotten this to work, I'd greatly appreciate the assistance. Apologies for any typos, I've been staring at this for most of the day.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...