我有一个在动态创建的跨度上触发的函数。
treeFuncItom(_event:Event, catType){
console.log('INSIDE COMPONENT', _event);
let myEvent = {};
if(catType == 'id'){
myEvent['value'] = _event['item']['dataItem']['_id'];
myEvent['module'] = 'id';
}else {
myEvent['module'] = 'tag';
myEvent['value'] = _event['item']['dataItem']['name'];
}
this.ItemChange.emit(myEvent);
}
我试图通过从angular4中的.spec.ts中传递虚拟事件来触发此功能。
it('Should raise ItemChange event, and set module to \'id\'', async () => {
let _event = {
item: {
dataItem: {
name: 'abcd'
},
index: 0
},
originalEvent: 'MouseEvent',
index: 0
};
fixture.detectChanges();
await fixture.whenStable();
let ee = JSON.stringify(_event);
let item = null;
component.ItemChange.subscribe(it => {
console.log('Int Test', it);
item = it;
});
component.treeFuncItom(new Event(ee), 'id');
expect(item).not.toBeNull();
expect(item.module).toEqual('id');
});
但是控制台出现错误:
ERROR: 'Unhandled Promise rejection:', 'Cannot read property 'dataItem' of undefined', '; Zone:', 'ProxyZone', '; Task:', 'Promise.then', '; Value:', TypeError{}, 'TypeError: Cannot read property 'dataItem' of undefined
at SidebarComponent.webpackJsonp../src/app/service-catalog/component/sidebar/sidebar.component.ts.SidebarComponent.treeFuncItom (http://localhost:9876/_karma_webpack_/webpack:/src/app/service-catalog/component/sidebar/sidebar.component.ts:26:40)
LOG: 'INSIDE COMPONENT', Event{isTrusted: false}
为什么被信任:false ,以及如何从spec.ts传递适当的事件
答案 0 :(得分:2)
async
和await
在这里,尝试一下:
it('should whatever', () => {
const mockEvent: any = {
item: {
dataItem: {
_id: 'item.dataItem.id',
name: 'item.dataItem.name'
}
}
};
const itemChange = spyOn(component.itemChange, 'emit');
component.treeFuncItom(mockEvent, 'id');
expect(itemChange).toHaveBeenCalledWith({
module: 'id',
value: mockEvent.item.dataItem._id
});
});