angular - Angular 单元测试 ActivatedRoute 参数订阅
问题描述
假设我订阅了组件中的路由参数:
this.route.params.subscribe((params) => {
// what the params object holds
// params.id1 params.id2
// what the current route looks like
//localhost/params.id1/params.id2
});
我将如何params.id2
在 Angular 中进行单元测试?示例:我想测试 params.id2 > 0
目前我已经这样做了:
// top of the describe
let route: ActivatedRoute;
//inside the TestBed.configureTestingModule
providers: [
{
provide: ActivatedRoute,
useValue: {
params: of({
id1: 1,
id2: 0,
}),
},
},
],
route = TestBed.inject(ActivatedRoute);
it('shouldn't be zero', () => {
// i want to check if params.id2 is not zero
expect(params.id2).not.toBe(0);
});
我没有任何使用单元测试的经验。我是否必须像在组件中那样订阅 route.params,或者我如何实现测试方法?
解决方案
它将为零,因为您在useValue
.
为了能够改变它,我会使用 a BehaviorSubject
,它是一个可观察的,并且可以在将来通过使用next
.
import { BehaviorSubject } from 'rxjs';
....
// top of the describe
let route: ActivatedRoute;
const paramsSubject = new BehaviorSubject({
id1: 1,
id2: 0,
});
//inside the TestBed.configureTestingModule
providers: [
{
provide: ActivatedRoute,
useValue: {
params: paramsSubject
},
},
]
route = TestBed.inject(ActivatedRoute);
it('should be zero', (done) => { // add done to let Jasmine know when you're done with the test
route.params.subscribe(params => {
expect(params.id2).toBe(0);
done();
});
});
it('should not be zero', (done) => {
paramsSubject.next({ id1: 1, id2: 3});
route.params.subscribe(params => {
expect(params.id2).not.toBe(0);
done();
});
});
但理想情况下,那些编写的测试并不好。您应该测试subscribe
组件内部发生的事情,并断言所发生的事情确实发生了。
推荐阅读
- reactjs - 使用 redux-saga 重定向反应路由器
- c# - 如何将 IEnumerable 转换为一个对象
- jasmine - 总是有一些测试用例得到 jasmine.DEFAULT_TIMEOUT_INTERVAL
- javascript - vue.js - 无法通过 css 更改 svg 的样式,并且在 dom 中它应用 element.style 而不是类名
- java - Jooq:如何将 Record 映射到具有相同列名的 Pojo 类?
- swift4 - 使用活动指示器(Swift4)在 UICollectionView 调用 API 中从滚动到最后一个单元格加载数据
- sql-server - 无法使用 FreeTDS 从 Linux VM 连接到 MSSQL Server
- flutter - 在平台/android-29 中找不到 Flutter 医生 -android sdk 文件
- jquery - 使用 Bootstrap 3 模式自动完成输入字段
- javascript - 在 excel 中打开 Excel 文件 url(来自源,不是下载的副本)