angular - 我如何模拟 id = this.route.snapshot.params.id; 在角度?
问题描述
我想模拟这段代码:(这是我的组件类中的一个属性)
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; });
解决方案
看起来你嵌套了useValue
2 次:
{
provide: ActivatedRoute,
useValue: {
// useValue again
useValue: {snapshot: {params: {'id': '1'}}},
},
}
代替
{
provide: ActivatedRoute,
useValue: {snapshot: {params: {'id': '1'}}},
}
推荐阅读
- excel - 将重复的数据字符串从 Outlook 提取到 Excel
- python - 当使用增量为三的 for 循环范围时,为什么第一个数字“分组”到自身?
- sql - Oracle - 为 3 亿条记录创建代理键
- sql-server - 使用存储过程连接到 SQL Server 后,我在“ExecuteNonQuery”上收到错误,为什么?
- c# - 我需要将小数或货币转换为 int
- python - Python - Selenium 无法处理警报
- arrays - Mongoose $push 用一个元素的新数组替换整个数组
- imagemagick - 使用 ImageMagick 比较像素移动但相似的图像
- objective-c - CGImageCreateWithImageInRect
- javascript - 动画结束后添加一个小反弹