【问题标题】:Testing Angular queryParams with Jasmine用 Jasmine 测试 Angular queryParams
【发布时间】:2021-02-03 13:54:05
【问题描述】:

StackBlitz example

我希望能够测试从一个视图传递到另一个视图的参数。我想测试一下参数是否存在以及参数是否与我提供的模拟测试数据匹配。

我对单元测试很陌生,在设置与激活的路由相关的测试并传递参数方面做了很多阅读。我认为我坚持的一点是“期望”。它给了我一个错误

Argument of type '{ urn: string[]; }' is not assignable to parameter of type 'Expected<Observable<Params>>'

组件

 export class SearchComponent implements OnInit {
  constructor(private route: ActivatedRoute, private router: Router) {
    this.getParam();
  }

  ngOnInit() {
  }

  getParam():void {
    this.route.queryParams.subscribe(params => {
      console.log(params["urn"]);
    });
}
}

规格

providers: [
        HttpClient,
        {
          provide: ActivatedRoute,
          useValue: {
            queryParams: of({
              urn: '123'
            })
          }
        }
      ],
...

  it('test queryParam in route', () => {
    const activatedRoute: ActivatedRoute = fixture.debugElement.injector.get(ActivatedRoute);

    activatedRoute.queryParams = of({ urn: '123' });

    fixture.detectChanges(); 
    //  tick();

    expect(activatedRoute.queryParams).toEqual({ urn: ['123'] }); // this line giving me trouble
  });

如果有人可以帮我看看我做错了什么 - 这是stackBlitz I came up with to demo

【问题讨论】:

    标签: angular unit-testing jasmine karma-jasmine


    【解决方案1】:

    这里:

    expect(activatedRoute.queryParams).toEqual({ urn: ['123'] })
    

    activatedRoute.queryParams 不是{ urn: ['123'] },而是一个Observable,它会触发这个值。

    你可以这样测试:

      /*
        Notice the extra "done" parameter. It is a function that you must call
        to indicate that the test is finished.
        It is necessary because we are testing an asynchronous method.
        This will prevent the test from exiting until the "done" method is called.
        Also, the test will fail if the done method is not called within 5s by default.
      */                                
      it('test queryParam in route', (done) => {
        [...]
    
        activatedRoute.queryParams.subscribe((value) => {
          expect(value).toEqual({ urn: ['123'] })
          done();
        })
    
      });
    

    【讨论】:

    • 谢谢 - 我不知道“完成”参数。我希望其他人觉得这个问题和答案有用
    • 我得到的唯一问题是“TypeError: Cannot read property 'subscribe' of undefined” - 但我可以看到 .subscribe 中的值是相等的。
    • @TomRudge 如果activatedRoute.queryParams 是undefined,您将无法到达回调的内部。我猜这个错误来自其他地方。你有行号或其他东西来帮助你找到这个错误的来源吗?它是来自.ts 还是来自spec.ts?
    • 这与@Arnaud 无关,但您仍然可以提供帮助吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-11-12
    • 2015-12-07
    • 2017-08-17
    • 2017-04-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多