qla*_*urf 1 unit-testing jasmine typescript karma-jasmine angular
假设我在组件中订阅了路由参数:
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
});
Run Code Online (Sandbox Code Playgroud)
我如何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);
});
Run Code Online (Sandbox Code Playgroud)
我没有任何使用单元测试的经验。我是否必须像在组件中那样订阅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();
});
});
Run Code Online (Sandbox Code Playgroud)
但理想情况下,那些编写的测试并不好。您应该测试组件内部发生的情况subscribe,并断言所发生的情况确实发生。
| 归档时间: |
|
| 查看次数: |
6805 次 |
| 最近记录: |