0

我想模拟这段代码:(这是我的组件类中的一个属性)

 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;   });
4

1 回答 1

0

看起来你嵌套了useValue2 次:

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

代替

{
  provide: ActivatedRoute,
  useValue: {snapshot: {params: {'id': '1'}}},
}
于 2020-12-26T12:37:59.003 回答