我想为组件中的某些功能添加测试。
在我的组件的 ngOnInit
中,我正在调用一个与 ChWidget
服务交互的函数并且它工作正常。但测试失败,因为 ChWidget
是 undefined
。
我试图模拟这一步,但对我来说效果不佳。
您能否建议是否有适当的处理方法?谢谢!
import { Component, OnInit, Input } from '@angular/core';
import { ActionsService } from '@ch-common/ch-common.module';
import { Product } from '@ch-products/product';
declare var window;
@Component({
selector: 'ch-container-header',
templateUrl: './container-header.component.html',
styleUrls: ['./container-header.component.scss']
})
export class ContainerHeaderComponent implements OnInit {
@Input() container: any;
product_group: any;
constructor(private actions: ActionsService) { }
ngOnInit() {
if (this.isProductList()) {
this.product_group = this.getGroupDetails(this.container);
}
}
getGroupDetails(container) {
var product = new Product(container.nodes[0].params.product)
var group_id = window.ChWidget.utils.getQueryStringParam("product-group-id", document.location.href)
return product.productBadgeIcons.find(obj => obj["group_id"] == group_id);
}
gotActions() {
return (this.container.params.actions || []).length > 0;
}
}
function setComponentParams(params) {
component.container = params;
}
function renderComponentWithParams(params) {
fixture = TestBed.createComponent(ContainerHeaderComponent);
component = fixture.componentInstance;
setComponentParams(params);
fixture.detectChanges();
compiled = fixture.debugElement.nativeElement;
}
fit('renders the show all if there is an action on the container and opens a product group page when clicking it', () => {
var container = {
nodes: [
{params: {
product: {
group_id: '5bc56a4ee9b43a9df8491',
group_name: 'Test Group'
}
}
}
],
params: {
container_role: 'product_list',
show_container_title: false,
title: 'my fancy title',
actions: [{type: 'openProduct', params: {id: '123'}}]
}
};
renderComponentWithParams(container);
fixture.detectChanges();
const elem = element.querySelector('.container-action-tile');
expect(elem).not.toBeNull();
const actionsService = TestBed.inject(ActionsService);
spyOn(actionsService, 'performActions');
elem.click();
fixture.detectChanges();
expect(actionsService.performActions).toHaveBeenCalledWith(
[{type: 'openProducts', params: {query_params: {filtered_group_id: '5bc56a4ee9b4351aa9df8491'}, title: 'Test Group'}}]
);
});
});
Cannot read property utils of undefined
答案 0 :(得分:1)
您必须模拟 window
对象才能拥有您想要的东西。
function renderComponentWithParams(params) {
fixture = TestBed.createComponent(ContainerHeaderComponent);
component = fixture.componentInstance;
window.ChWidget = {};
window.ChWidget.utils = {};
window.chWidget.utils.getQueryStringParam = () => 'the id you want';
setComponentParams(params);
fixture.detectChanges();
compiled = fixture.debugElement.nativeElement;
}
it('renders the show all if there is an action on the container and opens a product group page when clicking it') {
...
}
afterEach(() => {
// Delete the ChWidget on the window because it will leak between tests.
// Every test, you should mock it again.
delete window.ChWidget;
});