I am looking to test a service that extends an abstract class. This abstract class includes the constructor and the method getId
.
Here is the code snippet:
export abstract class ClientCacheService {
private subscriptionId: string;
protected getId(key :string, prefix:string=""): string {
return `${this.subscriptionId}_${prefix}_${key}`;
}
constructor() {
this.subscriptionId = new AppContextService().organizationKey();
}
abstract setCache(key :string, prefix:string, object: ICacheble): void;
abstract getCache(key :string, prefix:string): ICacheble | null;
abstract removeCache(key :string, prefix:string): void;
}
@Injectable()
export class MemoryCacheService extends ClientCacheService {
constructor() {
super();
}
setCache(key: string, prefix: string, object: ICacheble): void {
window[this.getId(key, prefix)] = JSON.stringify(object);
}
getCache(key: string, prefix: string): ICacheble | null {
let res = window[this.getId(key, prefix)];
return res ? JSON.parse(res) : null;
}
removeCache(key: string, prefix: string): void {
delete window[this.getId(key, prefix)];
}
}
I have two options:
- Mock the
ClientCacheService
- Mock the
AppContextService
which is inside the constructor ofClientCacheService
My preference is the second option (mocking the AppContextService
), but I am open to considering the first option as well.
In the provided code below, I attempted to mock the ClientCacheService
, however, the MemoryCacheService does not have a defined subscriptionId
, causing my 'should be possible set cache' test case to fail.
import { MemoryCacheService } from "./memory-cache.service";
import { ICacheble } from "interfaces/cacheble.interface";
import { TestBed, inject } from "@angular/core/testing";
import { ClientCacheService } from "./client-cache.service";
export class CacheableObject implements ICacheble {
prop1: String;
prop2: Boolean;
constructor() {
this.prop1 = "prop1 testable";
this.prop2 = true;
}
equals(cacheableObject: CacheableObject): boolean {
return this.prop1 === cacheableObject.prop1 &&
this.prop2 === cacheableObject.prop2;
}
}
export class MockClientCacheService {
private subscriptionId: string;
constructor() {
this.subscriptionId = "Just a subscription";
}
}
describe('MemoryCacheService Test cases', () => {
let memoryCacheService: MemoryCacheService;
beforeEach(() => {
TestBed.configureTestingModule({
providers: [
{ provide: ClientCacheService, useClass: MockClientCacheService },
MemoryCacheService
]
});
});
it('should be possible to instantiate it', inject([MemoryCacheService], (memoryCacheService:MemoryCacheService)=> {
expect(memoryCacheService).toBeDefined();
}));
it('should be possible to set cache',()=> {
let cacheableObject: CacheableObject = new CacheableObject();
memoryCacheService.setCache("test_key", "test_prefix", cacheableObject);
let storedObject: CacheableObject = memoryCacheService.getCache("test_key", "test_prefix") as CacheableObject;
expect(storedObject.equals(cacheableObject)).toBeTruthy();
});
});