如何测试ngOnInit中是否取决于路由参数的语句

时间:2019-08-29 21:19:45

标签: angular angular2-testing

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

1 个答案:

答案 0 :(得分:1)

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

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

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

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

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

相关问题