【问题标题】:Angular unit test ActivatedRoute params subscriptionAngular 单元测试 ActivatedRoute 参数订阅
【发布时间】:2021-06-28 12:26:17
【问题描述】:

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

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

【问题讨论】:

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


    【解决方案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 内部发生的事情,并断言发生的事情确实发生了。

    【讨论】:

    • 我知道它们不是很好的测试,它们只是虚拟测试。但是有没有办法我可以在不订阅的情况下做到这一点?例如,spyOn 是否可以工作,如果可以,我将如何使用它 (spyOn('route.params', 'subscribe).and.returnValue({id1: 1, id2: 0}))
    • 不,那行不通。您只能 spyOn 类的方法/函数,而 params 是一个可观察的实例变量,因此 spyOn 将不起作用。
    猜你喜欢
    • 1970-01-01
    • 2022-01-01
    • 2020-09-23
    • 2017-11-23
    • 1970-01-01
    • 1970-01-01
    • 2018-10-03
    • 2022-11-23
    • 1970-01-01
    相关资源
    最近更新 更多