angular - 如何对来自activatedRoute的oninit数据是否可用进行单元测试
问题描述
我是 angular 单元测试的新手。我们正在使用 jest 并且真的不知道如何测试路由是否正在返回数据。我想知道我们是否可以进行单元测试以检查数据是否以角度从路线返回。非常感谢任何帮助
在我的课上 component.ts
public data$: Observable<Data>;
public salariesPerHours: salariesPerHoursViewModel[];
private destroy$ = new Subject<boolean>();
constructor(private activatedRoute: ActivatedRoute) {}
public ngOnInit(): void {
this.data$ = this.activatedRoute.data;
this.data$?.pipe(takeUntil(this.destroy$)).subscribe((data: Data) => {
this.salariesPerHours= data?.Salary?.salaryPerHour;
});
}
在测试类组件中
import { ActivatedRoute, Data } from '@angular/router';
import { salariesPerHoursViewModel,SalaryType } from 'lib/store/store.barrel';
import { Subject } from 'rxjs';
import { SalaryComponent } from './salary.component';
const dataMock: salariesPerHoursViewModel[] = [
{
year:2018,
salaryModifications:[
{
date:'2018-02-01T00:00:00',
type: 'Salary',
action:[
{
logical :'0212834',
label:''
}
]
},
]
}
]
describe('SalaryComponent', () => {
let component: SalaryComponent;
let activatedRoute: ActivatedRoute;
beforeEach(() => {
activatedRoute = new ActivatedRoute();
component = new SalaryComponent(activatedRoute);
});
describe('ngOnInit', () => {
beforeEach(() => {
jest.spyOn(component, 'ngOnInit');
});
//how to test if data is coming up
});
describe('ngOnDestroy', () => {
test('should complete the destroy observable', () => {
component['destroy$'].next = jest.fn();
component['destroy$'].complete = jest.fn();
component.ngOnDestroy();
expect(component['destroy$'].next).toHaveBeenCalledWith(true);
expect(component['destroy$'].complete).toHaveBeenCalled();
});
});
});
解决方案
在 ngOnInit 内部使用了activatedRoute,因此后者不是被监视而是直接测试。
现在,你的输入和输出是什么?this.activatedRoute.data 是输入,this.salariesPerHours 是输出。
因此,在调用 ngOnInit 之前,您应该设置输入:
this.activatedRoute.data = of(<mock containing Salary.salaryPerHour>);
并且,在调用 ngOnInit 之后,您应该检查 this.salariesPerHours 与预期值:
expect(this.salariesPerHours).toBe(<Salary.salaryPerHour from mock>);
重要的是要观察 this.activatedRoute.data 分配了一个同步可观察('of' 运算符)以允许在订阅后立即调用回调(分配 this.salariesPerHours),这使得测试可控。
推荐阅读
- javascript - JavaScript 正则表达式两个字符串数字由 (:) 分隔的单个最大最小值计算
- javascript - 如何在 angularjs 中为事件广播找到 $on?
- html - 使用 BeautifulSoup 将 HTML 编码的 JSON 转换为 JSON
- oracle-sqldeveloper - 如何在 SQL 开发人员中调用存储过程,其中参数是带有回车的长字符串
- c# - 如何使用带有 at 命令的 GSM 调制解调器发送和读取 SMS
- javascript - 如何解决图片上传问题
- python - 当迭代次数增加时,Cupy 会变慢
- applescript - 如何将 Automator 中的多个变量作为文本传递/粘贴到 Google Chrome 中
- android - 如何避免默认选中BottomNavigationView集中的第一项
- javascript - 我的下拉菜单没有下拉(它出现在侧面)以及如何粘贴栏