首页 > 解决方案 > 如何在 ngOnInit 中测试依赖于路由参数的 if 语句

问题描述

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

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}},
];

标签: angularangular2-testing

解决方案


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

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

TestBed.configureTestingModule中,提供此值而不是ActivatedRoute。如下修改您的提供程序:

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

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


推荐阅读