Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jasmine Spy On a Typescript Class Get() or Set() function

I am using Jasmine 2.9 and I have not have problems spying on a function whether it was public or private but I am having difficulty trying to spy on a get or set function on the class level.

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;
  }
}

Solutions I tried:

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);

Currently I have not found a solution to this online but will continue looking. I know the get or set functions creates a variable so I thought perhaps solution 4 would have worked but still no.

Update

(The code above is also updated).

Trying the update to return a string and using the following jasmine give me an error:

spyOnProperty(RandomService, 'dogsFullName', 'get').and.returnValue('Frank');

Expected a spy, but got 'Frank'

As well as for the function isDogAlive I get the following:

<toHaveBeenCalled> : Expected a spy, but got true.

I understand it is giving me the correct value but if I spyOn it then should it not be a spy?

like image 667
L1ghtk3ira Avatar asked Mar 06 '23 11:03

L1ghtk3ira


1 Answers

Instead of returning a boolean value of true, try to return something like "frank". The return value is most likely expecting a string value rather than a boolean, which would be the cause of the issue.

let spyTemp = spyOnProperty(RandomService, 'dogsFullName', 'get').and.returnValue("frank");

then

expect(spyTemp).toHaveBeenCalled();
like image 166
thenolin Avatar answered Mar 15 '23 22:03

thenolin