angular - 如何在 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}},
];
解决方案
ActivatedRoute
你可以在你的测试中模拟。ActivatedRoute
在规范文件中创建一个具有您需要的值的对象。
const mockActivatedRoute = {
snapshot: {
data: {
cached: true
}
}
}
在TestBed.configureTestingModule
中,提供此值而不是ActivatedRoute
。如下修改您的提供程序:
providers: [
APIService,
{ provide: ActivatedRoute, useValue: mockActivatedRoute }
]
现在,您的组件将在单元测试期间将这个模拟值用于 ActivatedRoute。
推荐阅读
- odoo - 安装模块后正常字段没有更新吗?
- c# - 如何在 NPOI 中使用系统颜色设置 excel 单元格背景颜色
- python-3.x - 为什么我在 pennylane 中收到设备功能的“TypeError”?
- spring-kafka - 使用 DeadLetterPublishingRecoverer 进行状态重试导致 RetryCacheCapacityExceededException
- vue.js - Facebook 登录错误:“FB”未使用 Vue.js 定义
- php - 在php中查询和排序数据
- javascript - 如何检查元素数组中选中复选框的数量?
- git - 将远程 repo url 从 https 更改为 ssh 安全吗?
- android - 为什么应用程序在后台时声音没有响起(Android 应用程序中的 Firebase 推送通知)?
- r - 从旧的 ggmap 数据中使用 getNOAA 创建新地图