MadCatm2 MadCatm2 - 2 years ago 124
TypeScript Question

How to test TypeScript abstract class with Jasmine

I have a very simple abstract class which I implement in my Angular service. I am trying to write some tests for it but cannot find any information about testing abstract classes in the Jasmine docs.

import { Page } from '../models/index';

import { Observable } from 'rxjs/Observable';

export abstract class ILayoutGeneratorService {
abstract generateTemplate(page: Page, deviceType: string ): Observable<string>;

The abstract class is implemented as follows:

export class DefaultLayoutGeneratorService implements ILayoutGeneratorService {
generateTemplate(page: Page, deviceType: string): Observable<string> {
return Observable.create((observer: any) => {
// do something with result.

I am wondering how I would write a basic isolated unit test that checks if the class above can be implemented and its single method called. I understand that I would somehow have to mock the implementation of the class, but I am not really sure how to go about this.

Answer Source

I'm not aware of an approach to automatically stub out an implementation of an abstract class in TypeScript. If you find one, that's a good bet. But with spyOn and related behaviors, Jasmine can at least help.

A couple approaches along those lines:

  1. You already have an implementation in your DefaultLayoutGeneratorService, so you could leverage that as your mock implementation as well, especially coupled with spyOn, e.g.:

    let defaultLayoutGeneratorService = new DefaultLayoutGeneratorService();
    spyOn(defaultLayoutGeneratorService, 'generateTemplate');

    If you need to test several specific outputs, you could use that together with .and.returnValue, e.g.:

  2. Or you could implement a separate mock. (Maybe because DefaultLayoutGeneratorService is difficult to instantiate, or just to decouple.) If you want to test specific outputs or just decouple test logic from the mock, you could still use spyOn as above.

Then call the various methods to be tested, like mock.generateTemplate(page, deviceType). And include whatever additional checks that you need, probably leveraging Jasmine's expect.
