【问题标题】:How do I mock id = this.route.snapshot.params.id; in angular?我如何模拟 id = this.route.snapshot.params.id;在角度?
【发布时间】: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


【解决方案1】:

看起来你嵌套了useValue 2 次:

{
  provide: ActivatedRoute,
  useValue: {
    // useValue again
    useValue: {snapshot: {params: {'id': '1'}}},
  },
}

而不是

{
  provide: ActivatedRoute,
  useValue: {snapshot: {params: {'id': '1'}}},
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-05
    • 2023-04-02
    • 1970-01-01
    相关资源
    最近更新 更多