简体   繁体   English

Angular 2测试错误无法读取未定义的属性“ forEach”

[英]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.

相关问题 错误类型错误:无法读取 Angular 中未定义的属性“forEach” - ERROR TypeError:Cannot read property 'forEach' of undefined in Angular 无法读取未定义错误 JavaScript 的属性“forEach” - Cannot read property 'forEach' of undefined error JavaScript 错误:TypeError:无法读取未定义的属性“forEach” - Error : TypeError: Cannot read property 'forEach' of undefined 错误:无法读取未定义的属性“ forEach” - Error : Cannot read property 'forEach' of undefined 使用Jest进行测试 - TypeError:无法读取未定义的属性'forEach' - Testing with Jest - TypeError: cannot read property 'forEach' of undefined Angular 7 - 错误错误:未捕获(承诺):类型错误:无法读取未定义的属性“forEach” - Angular 7 - ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'forEach' of undefined 无法读取未定义的属性“forEach” - Cannot read property 'forEach' of undefined 为什么Angular 5 Transition抛出AppComponent.html:2 ERROR TypeError:无法读取未定义的属性'forEach' - Why does Angular 5 Transition throw AppComponent.html:2 ERROR TypeError: Cannot read property 'forEach' of undefined Angular 4错误:无法读取未定义的属性“ push” - Angular 4 error: Cannot read property 'push' of undefined 错误TypeError:无法读取undefined |的属性“0” Angular 4 - ERROR TypeError: Cannot read property '0' of undefined | Angular 4
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM