使用 Jasmine 测试 Angular queryParams

Testing Angular queryParams with Jasmine

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

这里:

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

  });