代码之家  ›  专栏  ›  技术社区  ›  ali akbar azizkhani

为activatedRoute数据创建测试

  •  9
  • ali akbar azizkhani  · 技术社区  · 7 年前

    我想为我的组件创建测试。我有一个路由器解析器,它在ng init中解析数据和读取数据。我想为此创建测试。如何创建此代码的测试

        @Component({
        selector: 'jhi-label-detail',
        templateUrl: './label-detail.component.html'
    })
    export class LabelDetailComponent implements OnInit {
    
        label: Label;
    
        constructor(
            private route: ActivatedRoute
        ) {
        }
    
        ngOnInit() {
            this.route.data.subscribe(({label}) => {
                this.label = label.body ? label.body : label;
            });
        }
    
    
    }
    

    路线是这样的

    {
            path: 'label/:id/view',
            component: LabelDetailComponent,
            resolve: {
                label: LabelResolve
            }
        }
    

    解决方法是

    @Injectable()
    export class LabelResolve implements Resolve<any> {
    
        constructor(private service: LabelService) {
        }
    
        resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
            const id = route.params['id'] ? route.params['id'] : null;
            if (id) {
                return this.service.find(id);
            }
            return new Label();
        }
    
    }
    
    2 回复  |  直到 7 年前
        1
  •  20
  •   Tomasz Kula    7 年前
    import { async, ComponentFixture, TestBed } from '@angular/core/testing';
    import { ActivatedRoute } from '@angular/router';
    import { of } from 'rxjs/observable/of';
    import { Observable } from 'rxjs/Observable';
    
    import { MyComponent } from './my-component.component';
    
    describe('MyComponent', () => {
      let component: MyComponent;
      let fixture: ComponentFixture<MyComponent>;
      const route = ({ data: of({ label: 'hello' }) } as any) as ActivatedRoute;
    
      beforeEach(
        async(() => {
          TestBed.configureTestingModule({
            declarations: [MyComponent],
            providers: [{ provide: ActivatedRoute, useValue: route }],
          }).compileComponents();
        }),
      );
    
      beforeEach(() => {
        fixture = TestBed.createComponent(MyComponent);
        component = fixture.componentInstance;
        fixture.detectChanges();
      });
    
      it('should set the label', () => {
        expect(component.label).toEqual('hello');
      });
    });
    

    这里需要注意的重要一点是,我们正在提供自己的 ActivatedRoute 在里面 TestBed.providers ,只有一个属性( data )我们的组件正在使用。

        2
  •  4
  •   dimitris maf    5 年前

    在angular 8+中有RouterTestingModule,您可以使用它来访问组件的ActivatedRoute或Router。您还可以将路由传递给RouterTestingModule,并为请求的路由方法创建间谍。

    例如,在我的组件中,我有:

    ngOnInit() {
        this.data = this.route.data
    }
    

    在我的测试中,我有:

      beforeEach(async(() => {
        TestBed.configureTestingModule({
          declarations: [ ProductLinePageComponent ],
          schemas: [NO_ERRORS_SCHEMA],
          imports: [
            RouterTestingModule.withRoutes([])
          ],
        })
        .compileComponents()
      }))
    
      beforeEach(() => {
        router = TestBed.get(Router)
        route = TestBed.get(ActivatedRoute)
        route.data = hot('(a)', {a: someData})
      })
    

    然后在“it”部分:

      it('should update', () => {
        const spyRoute = spyOn(route.snapshot.paramMap, 'get')
        spyRoute.and.returnValue('21')
        fixture = TestBed.createComponent(ProductLinePageComponent)
        component = fixture.componentInstance
        fixture.detectChanges()
        // here you can test the functionality which is triggered by route data
        const expected = cold('(a)', {a: someData})
        expect(component.data).toBeObservable(expected)
      })