我在其他帖子中看到了同样的错误,但它们对我不起作用。
我有一个 Angular 组件,我需要从 url 中读取一个 queryParam,例如http://localhost:4200/sample-page?page=3
我想将数字 3 存储到一个组件局部变量中。
/**
* Set page by url parameter
*/
export const setPaginationMarkByUrlParam = (activatedRoute): number => {
// Get page param from Url to set pagination page
const pageParam = activatedRoute.snapshot.queryParams;
return pageParam.page ? Number(pageParam.page) : 1;
};
这个函数在另一个文件中,我把activeRoute作为参数,它来自我想要获取queryParam的组件的ngOnInit。
ngOnInit() {
this.page = setPaginationMarkByUrlParam(this.activatedRoute);
}
此代码运行良好,但是当 Jenkins 管道运行npx jest
测试时,我收到以下消息:
TypeError: Cannot read property 'queryParams' of undefined
我的规格:
beforeEach(() => {
TestBed.configureTestingModule({
...,
providers: [
{
provide: ActivatedRoute,
useValue: {
data: {
subscribe: (fn: (value: Data) => void) =>
fn({
pagingParams: {
predicate: 'id',
reverse: false,
page: 0
}
})
}
}
}
]...
it('Should call load all on init', () => {
// GIVEN
const headers = new HttpHeaders().append('link', 'link;link');
spyOn(service, 'query').and.returnValue(
of(
new HttpResponse({
body: [new DataSource(123)],
headers
})
)
);
// WHEN
comp.ngOnInit();
// THEN
expect(service.query).toHaveBeenCalled();
expect(comp.dataSources[0]).toEqual(jasmine.objectContaining({ id: 123 }));
});
comp.ngOnInit();
测试在功能上失败。
我没有任何类型的私有变量,作为参数的activeRoute,我尝试了公共和私有。
查看 StackOverflow 和 GitHub 问题,我无法解决这个问题。
非常感谢!