如何使用 ActivatedRoute 测试我的组件?

How to test my component with ActivatedRoute?

我正在尝试使用 2 个解析器(pagesResolver 和 UploadResolver)测试一个组件:

我的组件:

export class AdminPagesComponent implements OnInit {
  fileUploads$: Observable<FileUpload[]>;
  pagesList$: Observable<Page[]>;
  constructor(
    private route: ActivatedRoute
  ) { }

  ngOnInit(): void {
    this.pagesSub = this.route.parent.data
      .pipe(
        map((data: { pages: Observable<Page[]> }) => {
          this.pagesList$ = data.pages
          return data.pages
        }),
        mergeMap(res => res.pipe(
          map(pages => {
            this.pagesService.setPages(pages);
            console.log(pages)
          })
        ))
      )
      .subscribe();
    this.uploadSub = this.route.parent.data
      .pipe(
        map((data: { upload: Observable<FileUpload[]> }) => {
          this.fileUploads$ = data.upload
          return data.upload
        })
      )
      .subscribe();
  }    
}

这是我的测试文件:

describe('AdminPagesComponent', () => {
  let component: AdminPagesComponent;
  let fixture: ComponentFixture<AdminPagesComponent>;
  const initialState = {};

  beforeEach(async () => {
    await TestBed.configureTestingModule({
      declarations: [AdminPagesComponent],
      imports: [],
      providers: [
        {
          provide: ActivatedRoute,
          useValue: {
            parent: {
              data: {

              }
            }
          }
        }
      ]
    })
      .compileComponents();
  });

  beforeEach(() => {
    fixture = TestBed.createComponent(AdminPagesComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });
});

如果我运行这样测试,我有这个业力错误:

TypeError: this.route.parent.data.pipe is not a function

我的组件工作正常,数据通过异步管道很好地传递到模板。 请问我怎样才能使我的测试成功?

你几乎成功了。在你的情况下,你需要 data 到 return 一个 Observable

import { of } from 'rxjs';
....
providers: [
        {
          provide: ActivatedRoute,
          useValue: {
            parent: {
              data: of({
                 pages: undefined,
                 upload: undefined // mock these two properties however you wish.
              }),
            }
          }
        }
      ]