Search code examples
angularangular-testts-mockito

check if setter was used


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.


Solution

  • 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.