1

我正在使用 Angular 2.1.0。

我有一个非常简单的异步服务:

@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()模拟异步行为。和使用它的类:

@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();
    }

}

我想为服务和组件编写单元测试。我已经阅读了 angular.io 教程。我需要额外的解释:(

对于测试组件我想:

  1. 测试开始时没有 div.c
  2. 打钩
  3. 检查 div.c 内容 = '值 1'
  4. 打钩
  5. 检查 div.c 内容 = '超值 2'

或者也许没有必要指出第 4 点和第 5 点,因为有双 2 和 3?

我知道使用异步服务测试组件有两种选择:使用存根服务或使用真实服务并监视关键功能。在我的情况下,我应该如何为这两种情况编写测试?

以及如何测试服务?我想避免等待 20 秒等待测试结果。

4

0 回答 0