0

I have a service to run unit tests as follows. It has two helper functions which use service params as follows.

Here is the service.ts file

export function storeToStorage<T>(key: string, item: T): void {
  this.storageService.libLocalStorage( 'set' ,key, item )
}

export function getFromStorage<T>(key: string): T {
  return this.storageService.libLocalStorage( 'get' ,key )
}


@Injectable({
  providedIn: 'root'
})
export class TableColumnService {
...
constructor(private storageService: LocalStorageService) {
    localStorage.removeItem('KEY');
    this._initializeColumns();
  }
...
}

Here Local storage service is service implemented separately for managing storage of the application. And application is running with out any error.

My implementation for service.spec.ts as follows

describe('TableColumnService', () => {
  let service: TableColumnService;
  let localStorageService: LocalStorageService;

 beforeEach(async (() => {
    TestBed.configureTestingModule({
      imports: [TestSharedModule],
      providers: [LocalStorageService]
    });
    service = TestBed.inject(TableColumnService);
    localStorageService = TestBed.inject(LocalStorageService);

  }));

  it('should be created', () => {
    expect(service).toBeTruthy();
  });

});

I am getting following error when running

Chrome Headless 90.0.4430.212 (Mac OS 10.15.7) TableColumnService should be created FAILED
        Failed: Cannot read property 'storageService' of undefined
            at <Jasmine>

I tried to spy external functions as follows. But giving errors

beforeEach(async (() => {
    TestBed.configureTestingModule({
      imports: [TestSharedModule],
      providers: [LocalStorageService]
    });
    service = TestBed.inject(TableColumnService);
    localStorageService = TestBed.inject(LocalStorageService);

    spyOn(storeToStorage, 'storeToStorage').and.returnValue({});
    spyOn(getFromStorage, 'getFromStorage').and.returnValue({});

  }));

It gives following error on spy functions

Argument of type '{}' is not assignable to parameter of type 'never'
Janith Widarshana
  • 3,213
  • 9
  • 51
  • 73

1 Answers1

0

I reckon you're not spying correctly; it should be something like below and yes, you have to make stroage service public in ts file. If you don't want to make it public you can also create a stub for this service in your spec file.

spyOn(service.storageService, 'storeToStorage').and.returnValue({});
ammadkh
  • 569
  • 3
  • 9
  • I made private variable public in ts file but it did not work. Ten tries to do answer of https://stackoverflow.com/questions/46549869/mocking-angular-service-class-properties-or-variables but, it needs to implement all the methods in service. Any idea ? – Janith Widarshana May 28 '21 at 09:33