1

I'm using Angular 2.1.0.

I have a very simple asynchronous service:

@Injectable()
export class Service {

    protected str: Subject<string>;

    constructor() {
        this.str = <Subject<string>>new Subject();
    }

    getStream(): Observable<string> {
        return this.str.asObservable();
    }

    emit() {
        setTimeout(() => {
            this.str.next('Value 1');
            setTimeout(() => {
                this.str.next('Super Value 2');
            }, 10000);
        }, 10000);
    }
}

emit() emulates async behavior. And class using it:

@Component({
    selector: 'my-app',
    template: '<div class="c" *ngIf="c">{{c}}</div>'
})
export class AppComponent {

    private c: string;

    constructor(private s: Service) { }

    ngOnInit() {
        this.s.getStream().subscribe(data => {
            this.c = data;
        });
        this.s.emit();
    }

}

I want to write unit tests for service and for component. I've read angular.io tutorial already. And I need additional explanations :(

For testing componentI want to:

  1. test there is no div.c at start
  2. tick
  3. check div.c content = 'Value 1'
  4. tick
  5. check div.c content = 'Super Value 2'

Or maybe there is no need to point 4 and 5 as there double 2 and 3?

I know that for testing components with async service there are 2 options: use stubbed service or use real service and spy on critical functions. How should I write tests for both scenarios in my case?

And how to test the service? I'd like to avoid waiting 20s for test result.

koral
  • 2,807
  • 3
  • 37
  • 65

0 Answers0