I have a problem with testing my service in Angular6. This service implements SessionStorage which I've obtained from 'ngx-webstorage-service' library. I'm using it to keep choosen products when user clicks on another tab. Unfortunately it's not working. The first test doesn't work (service should be created). How should I mock the service and add InjectionToken?
I've tried to declare mock session object as StorageService, but Angular gives me an error. It's my first usage of this library in tests.
My constructor service looks like this:
import { Injectable, Inject, InjectionToken } from '@angular/core';
import { StorageService } from 'ngx-webstorage-service';
const STORAGE_KEY = 'productId';
export const MY_PRODUCTS_SERVICE_STORAGE =
new InjectionToken<StorageService>('MY_PRODUCTS_SERVICE_STORAGE');
@Injectable({
providedIn: 'root'
})
export class ProductService {
productIds: number[] = [];
constructor(@Inject(MY_PRODUCT_SERVICE_STORAGE) private storage: StorageService) {
const ids: number[] = this.storage.get(STORAGE_KEY);
if (typeof ids !== 'undefined') {
this.productIds= ids;
}
}
}
My test spec file:
import { TestBed, inject } from '@angular/core/testing';
import { ProductService, MY_PRODUCT_SERVICE_STORAGE } from './product.service';
import { StorageService, SESSION_STORAGE } from 'ngx-webstorage-service';
describe('ProductService ', () => {
let service: ProductService;
const mockSession = {
get: () => '',
set: () => null,
has: () => true,
remove: () => null,
clear: () => null,
withDefaultTranscoder: () => null
} as StorageService;
beforeEach(() =>
service = TestBed.get(ProductService));
TestBed.configureTestingModule({
providers: [
ProductService,
{ provide: MY_PRODUCTS_SERVICE_STORAGE, useExisting: SESSION_STORAGE }
]
});
it('should be created', inject([mockSession], () => {
expect(service).toBeTruthy();
}));
});
Expected output is to create the service, but unfortunately I'm obtaining error from angular tests: Error: StaticInjectorError(DynamicTestModule)[InjectionToken MY_PRODUCTS_SERVICE_STORAGE]: StaticInjectorError(Platform: core)[InjectionToken MY_PRODUCTS_SERVICE_STORAGE]: NullInjectorError: No provider for InjectionToken MY_PRODUCTS_SERVICE_STORAGE!
I' ve replaced:
get: () => ''
to:
get: () => []
and:
useExisting: SESSION_STORAGE
to:
useValue: mockSession
and:
it('should be created', inject([mockSession], () => {
expect(service).toBeTruthy();
}));
to:
it('should be created', () => {
expect(service).toBeTruthy();
});
and it finally works.