为 activatedRoute 数据创建测试

create test for activatedRoute data

我想为我的组件创建测试。我有在 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();
    }

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

这里要注意的重要一点是,我们在 TestBed.providers 中提供了我们自己的 ActivatedRoute 实现,其中只有一个 属性 (data)由我们的组件使用。

在 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)
  })