Renewed my website with the use of abstract classes
Table of contents

Great to do and great to see how to make abstractions using typescript and employ that in the code to make switching of implementations really easy. It is a very old but still very relevant concept of S.O.L.I.D principles. Single Responsibility, Open-Closed, Liskov Substitution, Interface Segregation and Dependency Injection. This is quite nice to see working in Angular. It kind of feels like working with Spring and MockK with Kotlin. Anyways this was the way I found out to use Jest in my unit tests, mock my services using the right abstractions and test all of my components creation in a very simple and elaborate way. One example is
describe('FullTimelineComponent', () => {
let testModule;
let techFilterStub: Partial<AbstractTechFilterService> = {
getTechFilters(_?: string): Observable<TechFilter[]> {
return AdapterService.createObservable([]);
}
};
let timelineStub: Partial<AbstractTimelineService> = {
getTimeline(page: number, pageSize: number, tags: string[], searchWord: string): Observable<TimelinePage> {
return AdapterService.createObservable({
page: page,
pageSize: pageSize,
pageTotal: 0,
timeline: []
})
}
};
beforeEach(async(() => {
testModule = TestBed.configureTestingModule({
imports: [
RouterTestingModule
],
declarations: [
FullTimelineComponent
],
providers: [
{provide: AbstractTechFilterService, useValue: techFilterStub},
{provide: AbstractTimelineService, useValue: timelineStub}
]
}).compileComponents();
}));
it("should create test module", () => {
let service = TestBed.inject(AbstractTechFilterService);
service.getTechFilters().subscribe(data => {
expect(data).toBe([]);
})
let timelineService = TestBed.inject(AbstractTimelineService);
timelineService.getTimeline(1, 2, [], "test").subscribe(data => {
expect(data).toBe({
page: 1,
pageSize: 2,
pageTotal: 0,
timeline: []
});
});
expect(testModule).toBeTruthy();
});
});
The use of provide above is what provides Injection into the components we want to test. We can then subscribe to mocked observers, which we can configure to perform tests. Very easy and very JVM language like.
Thank you!
I hope you enjoyed this article as much as I did making it!
Please leave a review, comments or any feedback you want to give on any of the socials in the links bellow.
I’m very grateful if you want to help me make this article better.
Thank you for reading!
Subscribe to my newsletter
Read articles from João Esperancinha directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
João Esperancinha
João Esperancinha
Software Engineer for 10+ Years, OCP11, Spring Professional 2020 and a Kong Champion