禁止为任何子组件测试调用父路由ngOnInit方法

时间:2019-01-23 08:56:51

标签: angular typescript jasmine karma-jasmine

我正在为我的角度分量编写测试。我有一个父组件和一个子组件。在父组件的ngOnInit中,我正在调用需要身份验证的后端函数。在测试子组件时,我不想加载或要防止父组件的ngOnInit。

部分路线如下:

{
    path: 'core',
    component: CoreComponent,
    children: [
        { path: '', redirectTo: 'home', pathMatch: 'full' },
        { path: 'home', component: HomeComponent },
        { 
            path: 'endpoint',
            component: EndpointComponent,
            children: [
                { path: '', redirectTo: 'machine', pathMatch: 'full' },
                { path: 'machine', component: MachineComponent }
            ]
        }
    ]
}

这里我正在测试MachineComponent。在CoreComponent的ngOnInit中,我正在调用后端函数。而且我想在测试MachineComponent时避免这种情况。

ngOnInit() {
    this.getMyDetails();
}

我的测试类如下:

describe('MachineComponent', () => {
  let component: MachineComponent;
  let endpointService: EndpointService;
  let fixture: ComponentFixture<MachineComponent>;

  let ep_data: any = {"name":"machine_ep"};

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [
        BrowserAnimationsModule,
        BrowserModule,
        FormsModule,
        HttpClientModule,
        CommonModule,
        RouterTestingModule.withRoutes([{ path: 'machine', component: MachineComponent }])
      ],
      declarations: [ MachineComponent ],
      providers: [
        EndpointService
      ],
      schemas: [ NO_ERRORS_SCHEMA ]
    })
    .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(MachineComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
    endpointService = TestBed.get(EndpointService);
    spyOn(endpointService, 'getEndpoints').and.returnValue(of([ep_data]));
  });

  it('should get endpoints', () => {
    component.getEndpoints();
    expect(component.endpoints[0].name).toBe("machine_ep");
    expect(endpointService.getEndpoints).toHaveBeenCalled();
  });

});

在拦截器中,如果任何服务调用失败并显示401代码,我将重定向到登录路由。

我的测试失败并出现错误:

HeadlessChrome 70.0.3538 (Linux 0.0.0) ERROR: 'Unhandled Promise rejection:', 'Cannot match any routes. URL Segment: 'login'', '; Zone:', 'ProxyZone', '; Task:', 'Promise.then', '; Value:', Error: Cannot match any routes. URL Segment: 'login'
Error: Cannot match any routes. URL Segment: 'login'

如何摆脱这个错误?

0 个答案:

没有答案