Angular 单元测试 ActivatedRoute params 订阅

时间:2021-04-01 13:42:39

标签: angular typescript unit-testing jasmine karma-jasmine

假设我订阅了组件中的路由参数:

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
});

我将如何在 Angular 中对 params.id2 进行单元测试?示例:我想测试 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,或者我如何实现测试方法?

1 个答案:

答案 0 :(得分:1)

它将为零,因为您在 useValue 中提供了一个静态零值。

为了能够更改它,我将使用 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 内部发生的事情并断言发生的事情确实发生了。