首页 > 解决方案 > 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,或者我如何实现测试方法?

标签: angulartypescriptunit-testingjasminekarma-jasmine

解决方案


它将为零,因为您在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组件内部发生的事情,并断言所发生的事情确实发生了。


推荐阅读