[英]Angular 2 Testing Error Cannot read property 'forEach' of undefined
I'm trying to test a component.ts: 我正在尝试测试component.ts:
import { ActivatedRoute, Params } from '@angular/router';
import { Location } from '@angular/common';
...
ngOnInit(): void {
this.route.params.forEach((params: Params) => {
let id = +params['id'];
...
}
the spec.ts code below: 下面的spec.ts代码:
describe('MyDetailComponent', () => {
beforeEach( async(() => {
addMatchers();
TestBed.configureTestingModule({
imports: [ MaterialModule, FormsModule ],
declarations: [ MyDetailComponent ],
providers: [
...
{ provide: RequestOptions, useClass: RequestOptionsStub },
{ provide: ActivatedRoute, useClass: RouterStub },
{ provide: Location },
{ provide: XHRBackend, useClass: MockBackend },
AppSettings,
Http,
ConnectionBackend,
Jsonp
]
})
.compileComponents()
.then(createComponent);
}));
and I'm getting the error: Failed: Uncaught (in promise): Error: Error in :0:0 caused by: Cannot read property 'forEach' of undefined TypeError: Cannot read property 'forEach' of undefined 并且我得到了错误:失败:未捕获(承诺):错误::0:0中的错误,原因是:无法读取未定义的属性'forEach'TypeError:无法读取未定义的属性'forEach'
How to fix this? 如何解决这个问题?
Found an answer in Angular2 RC5 Mock Activated Route Params : 在Angular2 RC5模拟激活的路线参数中找到了答案:
import { Observable } from 'rxjs/Rx';
...
{ provide: ActivatedRoute, useValue: { 'params': Observable.from([{ 'id': 1 }]) } }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.