1

I have a public method A() in service which modifies a private data member of that service.

A() {
  //call http
  // change private data member using call's result
}

I am unit testing a component that uses this service and thus want to change the data member by using spyOn.and.callFake() functionality of Jasmine. However, as the data member is private, I can't access it in the component using the service object. I don't want to make the data member public for the purpose of a test.

What should be the best practice here?

AvinashK
  • 3,309
  • 8
  • 43
  • 94

1 Answers1

1

I am making the assumption that you are using typescript and that the class member you are trying to access is marked by the private keyword.

Since typescript is fundamentally a typing layer on top of Javascript, the JS runtime will not prevent you from accessing private members of a class. It is only that the typescript compiler will complain if yo try to do it.

If you want to access a private member without the compiler complaining, you can convert it to an any type, in the following way:

spyOn(myObj, 'A').and.callFake(arg => {
  (this as any).myPrivateProperty = this.doSomething();
};
Andrew Eisenberg
  • 28,387
  • 9
  • 92
  • 148