Testing Angular 2 parent route

前端 未结 1 1288
广开言路
广开言路 2020-12-21 08:51

I have a component that accesses a parent route value like this:

  ngOnInit() {
    this.route.parent.parent.params.subscribe(params => {
      this.place         


        
相关标签:
1条回答
  • 2020-12-21 09:25

    I ended up solving it the latter way: providing a fake route. Here's what I did.

    Pay attention to the parts that mention mockActivatedRoute.

    /* tslint:disable:no-unused-variable */
    import { async, ComponentFixture, TestBed } from '@angular/core/testing';
    import { RouterTestingModule } from '@angular/router/testing';
    import { ActivatedRoute } from '@angular/router';
    import { By } from '@angular/platform-browser';
    import { DebugElement } from '@angular/core';
    import { Observable } from 'rxjs/Observable';
    import 'rxjs/add/observable/of';
    
    import { MockPlaceService } from '../../../testing/mock-place.service';
    
    import { DinerReviewListComponent } from './diner-review-list.component';
    import { PlaceService } from '../place.service';
    
    let mockPlaceService = new MockPlaceService();
    
    class MockActivatedRoute {
      parent: any;
      params: any;
    
      constructor(options) {
        this.parent = options.parent;
        this.params = options.params;
      }
    }
    
    let mockActivatedRoute = new MockActivatedRoute({
      parent: new MockActivatedRoute({
        parent: new MockActivatedRoute({
          params: Observable.of({ id: '1' })
        })
      })
    });
    
    describe('DinerReviewListComponent', () => {
      let component: DinerReviewListComponent;
      let fixture: ComponentFixture<DinerReviewListComponent>;
    
      beforeEach(async(() => {
        TestBed.configureTestingModule({
          declarations: [
            DinerReviewListComponent
          ],
          imports: [RouterTestingModule]
        })
        .overrideComponent(DinerReviewListComponent, {
          set: {
            providers: [
              { provide: PlaceService, useValue: mockPlaceService },
              { provide: ActivatedRoute, useValue: mockActivatedRoute }
            ]
          }
        })
        .compileComponents();
      }));
    
      beforeEach(() => {
        fixture = TestBed.createComponent(DinerReviewListComponent);
        component = fixture.componentInstance;
        fixture.detectChanges();
      });
    
      it('should create', () => {
        expect(component).toBeTruthy();
      });
    });
    
    0 讨论(0)
提交回复
热议问题