Renewed my website with the use of abstr ...

Renewed my website with the use of abstract classes

Mar 25, 2022

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.

¿Te gusta esta publicación?

Comprar João Esperancinha un café

More from João Esperancinha