【发布时间】:2021-03-19 23:08:32
【问题描述】:
我想模拟这段代码: (这是我的组件类中的一个属性)
id = this.route.snapshot.params.id;
我的ActivatedRoute 在我的测试中需要它,我得到的错误是
无法读取未定义的“路由”属性。
我对此的嘲讽是:
TestBed.configureTestingModule({
// The declared components needed to test the UsersComponent.
declarations: [
MatchEditComponent, // The 'real' component that we will test
// RouterLinkStubDirective, // Stubbed component required to instantiate the real component.
],
imports: [FormsModule],
//
// The constructor of our real component uses dependency injected services
// Never provide the real service in testcases!
//
providers: [
{ provide: AuthService, useValue: authServiceSpy },
{ provide: AlertService, useValue: alertServiceSpy },
{ provide: Router, useValue: routerSpy },
{ provide: MatchService, useValue: matchServiceSpy },
// { provide: StudioService, useValue: studioServiceSpy },
{
provide: ActivatedRoute,
useValue: {
useValue: {snapshot: {params: {'id': '1'}}}
},
},
],
}).compileComponents();
fixture = TestBed.createComponent(MatchEditComponent);
component = fixture.componentInstance; });
【问题讨论】:
-
再次确认您收到的错误?
Cannot read property ??? of undefined? -
什么意思?
-
这是错误:在 afterAll TypeError 中引发错误:无法读取未定义的属性“路由”
-
在您的
imports数组中添加RouterTestingModule -
感谢您的回答,但它给出了同样的错误。这是现在的样子:导入:[FormsModule, RouterTestingModule, HttpClientModule],
标签: angular unit-testing mocking jasmine angular-activatedroute