2

I am looking for a TDD way of wrapping a native JavaScript class into an Angular 2 service. Now, I know that there are lots of discussions for doing this with Angular 1.x, however, none of them address this issue with Angular 2 or even with TDD in mind.

I need to wrap nanobar.js into an Angular 2 service. So, since I didn't write the library, I can't (won't) go and make it into an Angular 2 service. Also, I don't need a factory, this is intended to be a singleton.

So here is my first attempt at this, as you can see below. However, the tester in me is screaming "this isn't testable"!

Since you can't (I don't think) give a service an instance of a JavaScript class as part of its constructor, I instantiated it in place. That makes this whole thing virtually not testable.

Is there a better way of doing this with Angular 2?

Nanobar interface wrapper in Nanobar.Service.ts:

import {Injectable} from 'angular2/core';

@Injectable()
export class NanobarService {
    private bar: any = null;

    constructor() {
        this.bar = new Nanobar();
    }

    public finish(): void {
        this.go(100);
    }

    public go(percent: number): void {
        this.bar.go(percent);
    }
}

Used in Preloader.Component.ts:

import {Component}      from 'angular2/core';
import {NanobarService} from './Nanobar.Service';

@Component({
    providers: [ 'NanobarService' ],
    selector: 'preloader',
    ...
})
export class PreloaderComponent {
    private nanobar: NanobarService = null;

    constructor(nanobar: NanobarService) {
        this.nanobar = nanobar;
    }
}
Community
  • 1
  • 1
Oliver Spryn
  • 16,871
  • 33
  • 101
  • 195
  • You could lazily instantiate Nanobar in the service and provide a getter/setter to set one, where you could inject a mock Nanobar – malix Feb 27 '16 at 19:42

0 Answers0