我有一个Angular 2组件我试图进行测试,但是我遇到了麻烦,因为数据是在ngOnInit函数中设置的,所以在单元测试中不能立即使用.
用户view.component.ts:
import {Component, OnInit} from 'angular2/core';
import {RouteParams} from 'angular2/router';
import {User} from './user';
import {UserService} from './user.service';
@Component({
selector: 'user-view',
templateUrl: './components/users/view.html'
})
export class UserViewComponent implements OnInit {
public user: User;
constructor(
private _routeParams: RouteParams,
private _userService: UserService
) {}
ngOnInit() {
const id: number = parseInt(this._routeParams.get('id'));
this._userService
.getUser(id)
.then(user => {
console.info(user);
this.user = user;
});
}
}
Run Code Online (Sandbox Code Playgroud)
user.service.ts:
import {Injectable} from 'angular2/core';
// mock-users is a static JS array
import {users} from …Run Code Online (Sandbox Code Playgroud) 我正在升级我们的Angular2应用程序以使用rc4,我开始在单元测试中出错:
无法在异步区域测试中使用setInterval
我的窗口小部件从其ngOnInit方法请求数据,并在发出请求时发出加载指示符.我的模拟服务在1ms后返回一些数据.
这是一个暴露问题的简化版本
import { inject, async, TestComponentBuilder, ComponentFixture} from '@angular/core/testing';
import {Http, Headers, RequestOptions, Response, HTTP_PROVIDERS} from '@angular/http';
import {provide, Component} from '@angular/core';
import {Observable} from "rxjs/Rx";
class MyService {
constructor(private _http: Http) {}
getData() {
return this._http.get('/some/rule').map(resp => resp.text());
}
}
@Component({
template: `<div>
<div class="loader" *ngIf="_isLoading">Loading</div>
<div class="data" *ngIf="_data">{{_data}}</div>
</div>`
})
class FakeComponent {
private _isLoading: boolean = false;
private _data: string = '';
constructor(private _service: MyService) {}
ngOnInit() {
this._isLoading = true;
this._service.getData().subscribe(data …Run Code Online (Sandbox Code Playgroud)