【问题标题】:How to test if statement in ngOnInit that depends on route param如何在 ngOnInit 中测试依赖于路由参数的 if 语句
【发布时间】:2019-08-29 21:19:45
【问题描述】:

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

【问题讨论】:

  • 我如何在测试中访问它?

标签: angular angular2-testing


【解决方案1】:

您可以在测试中模拟 ActivatedRoute。在 spec 文件中的 ActivatedRoute 中使用您需要的值创建一个对象。

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

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

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

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

【讨论】:

  • 谢谢。是否可以将其设为可选,以便仅在我在测试中指定时使用cached,以便我可以同时测试ifelse?如果我这样做,它永远不会进入else 语句
  • 可以在测试else case之前修改mockActivatedRoute的值——mockActivatedRoute.snapshot.data.cached = false;
猜你喜欢
  • 1970-01-01
  • 2018-04-05
  • 2017-12-08
  • 2021-01-28
  • 1970-01-01
  • 2018-04-19
  • 2015-08-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多