如何测试 ngOnInit 中依赖于路由参数的 if 语句

How to test if statement in ngOnInit that depends on route param

我的 Angular 8 网络应用程序有一个组件可以根据路线执行不同的操作。在 ngOnInit 中,我使用路由数据来检查 cached 参数是否存在。我正在尝试编写一个将 cached 设置为 true 的单元测试,以便它进入 ngOnInit 中的 if 语句,但它不起作用。我做错了什么?

home.component.ts

cached = false;

constructor(private backend: APIService, private activatedRoute: ActivatedRoute) { }

ngOnInit() {
  this.cached = this.activatedRoute.snapshot.data['cached']; 
  if (this.cached)
  {
    this.getCached();
  }
  else
  {
    this.fetchFromAPI();
  }
}

home.component.spec.ts

describe('HomeComponent', () => {
  let component: HomeComponent;
  let fixture: ComponentFixture<HomeComponent>;
  let service: APIService;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [
        HttpClientTestingModule,
        RouterTestingModule,
      ],
      declarations: [
        HomeComponent,
      ],
      providers: [
        APIService
      ]
    })
    .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(HomeComponent);
    component = fixture.componentInstance;
    service = TestBed.get(APIService);
    fixture.detectChanges();
  });

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

   it('should go into if cached statement', fakeAsync(() => {
    component.cached = true;
    component.ngOnInit();
    const dummyData = [
      { id: 1, name: 'testing' }
    ];

    spyOn(service, 'fetchCachedData').and.callFake(() => {
      return from([dummyData]);
    });

    expect(service.fetchCachedData).toHaveBeenCalled();
  }));

})

路由器模块

const routes: Routes = [
  { path: 'home', component: HomeComponent },
  { path: '', redirectTo: 'home', pathMatch: 'full' },
  { path: 'view-cache', component: HomeComponent, data: {cached: true}},
];

您可以在测试中模拟 ActivatedRoute。在规范文件的 ActivatedRoute 中创建一个具有所需值的对象。

const mockActivatedRoute = {
  snapshot: {
    data: {
      cached: true
    }
  }
}

TestBed.configureTestingModule 中,提供此值而不是 ActivatedRoute。按如下方式修改您的提供商:

providers: [
    APIService,
    { provide: ActivatedRoute, useValue: mockActivatedRoute }
]

现在您的组件将在单元测试期间将此模拟值用于 ActivatedRoute。