Testing Angular queryParams with Jasmine



StackBlitz示例

我希望能够测试从一个视图传递到另一个视图的参数。我想测试一下参数是否在那里,并且参数是否与我给它的模拟测试数据匹配。

我对单元测试很陌生,做了很多关于激活路由和传递参数的设置测试的阅读。我想我被"期望"卡住了。提示错误

Argument of type '{ urn: string[]; }' is not assignable to parameter of type 'Expected<Observable<Params>>'
<<p>组件/strong>
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演示

此处:

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

添加,因为这是搜索angular test query params jest时的最高结果

如果您在组件中使用const { params: { id } } = this.route.snapshot。您还应该定义包含snapshot属性的mockActivatedRoute

const mockActivatedRoute = { snapshot: { params: of({ id: 'test-id' })} };否则,您可能会得到类似TypeError: Cannot read property 'params' of undefined

的错误。

最新更新