L1g*_*ira 4 unit-testing jasmine typescript karma-jasmine angular
我正在使用 Jasmine 2.9 并且我在监视一个函数时没有问题,无论它是公共的还是私有的,但是我在尝试监视类级别的getorset函数时遇到了困难。
private class RandomService {
public dogsHealth = 0;
private get personsFullName(): string {
return firstName + lastname;
}
private set personsLocation(address: string, city: string, country: string): string {
return address + city + country;
}
public get dogsFullName(): string {
return dogFirstName + dogLastName;
}
public get isDogAlive(): boolean {
return dogsHealth <= 0 ? true : false;
}
}
Run Code Online (Sandbox Code Playgroud)
我试过的解决方案:
spyOnProperty(RandomService, 'dogsFullName', 'get').and.returnValue(true);
spyOnProperty(RandomService, 'dogsFullName').and.returnValue(true);
spyOn(RandomService, 'dogsFullName').and.returnValue(true);
spyOnProperty(RandomService.dogsFullName, 'dogsFullName', 'get').and.returnValue(true);
Run Code Online (Sandbox Code Playgroud)
目前我还没有在网上找到解决方案,但会继续寻找。我知道 get 或 set 函数会创建一个变量,所以我认为解决方案 4 可能会起作用,但仍然没有。
(上面的代码也更新了)。
尝试更新以返回一个字符串并使用以下 jasmine 给我一个错误:
spyOnProperty(RandomService, 'dogsFullName', 'get').and.returnValue('Frank');
Run Code Online (Sandbox Code Playgroud)
Expected a spy, but got 'Frank'
除了功能,isDogAlive我还得到以下信息:
<toHaveBeenCalled> : Expected a spy, but got true.
Run Code Online (Sandbox Code Playgroud)
我知道它给了我正确的价值,但如果我是spyOn它,那么它不应该是间谍吗?
不要返回布尔值 true,而是尝试返回诸如“frank”之类的内容。返回值很可能需要字符串值而不是布尔值,这将是问题的原因。
let spyTemp = spyOnProperty(RandomService, 'dogsFullName', 'get').and.returnValue("frank");
Run Code Online (Sandbox Code Playgroud)
然后
expect(spyTemp).toHaveBeenCalled();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3305 次 |
| 最近记录: |