0

I have a setter/getter in my service

export class fooService {
  set foo(value: number): void {
    this._privateFoo = value;
  }
  get foo(): number {
    return this._privateFoo;
  }

Now i mocked the service using ts-mockito and want to check if the setter has been called. I tried checking the variable via the getter on the instance but this does not return my value.

component (FooComponent):

ngOnInit() {
  this.fooService.foo = 2;
  console.log('Foo Service is now:', this.fooService.foo);

unit test:

mockFooService = mock(FooService);
fooService = instance(mockFooService);
...
TestBed.configureTestingModule({
 declarations: [ FooComponent ],
  providers: [
    { provide: FooService: useValue: fooService }
...

component.ngOnInit();
expect(fooService.foo).toEqual(2);

The Test prints Foo Service is now: 2 but the expect fails with Expected null to equal 2.

Andresch Serj
  • 35,217
  • 15
  • 59
  • 101

2 Answers2

1

My Problem was obvious: If i mock the service, it is not working anymore. What i should do is either mock a setter and check if it is called or use the actual service.

Andresch Serj
  • 35,217
  • 15
  • 59
  • 101
  • Depends on how complex your service is in your testing, if it has alot of dependencies that actually has nothing to do what you wanna test I would go with mocking the service – Lucho Apr 03 '19 at 10:55
0

Use setter and getter together.

set foo(value: number): void {
  this._privateFoo = value;
}

get foo(): number{
  return this._privateFoo;
}
miladfm
  • 1,508
  • 12
  • 20