我有角度2组件 - 列表,其中包含项目。它是可过滤的,支持2个事件:过滤 - 在过滤过程发生之前;过滤 - 过滤过程发生后。 以下是实施:
@Output() filtering = new EventEmitter(false); // synchronous event emitter
@Output() filtered = new EventEmitter(); // async event emitter
filter() {
filteringArgs = { cancel: false };
this.filtering.emit(filteringArgs);
// Because the emitter is synchronous, the filtering handler will be executed now
// and then the execution of filter function will continue from here
if(filteringArgs.cancel) {
return;
}
// Filtering is happens here
var result = { /* result of filtering */ };
filteredArgs = { result: result }
this.filtered.emit(filteredArgs);
}

当我使用以下处理程序时:
filteringHandler(args) { args.cancel = true; }

在其父组件中取消过滤过程 - 它按预期工作:没有过滤器发生。 所以我想测试它并编写以下测试:
it('should cancel emitted filter events',
async(inject([TestComponentBuilder], (tcb: TestComponentBuilder) => {
var template = '<list (filtering)="filteringHandler($event)"><list-item>Item 1</list-item><list-item>Item 2</list-item><list-item>Item 3</list-item></list>';
return tcb.overrideTemplate(ListTestComponent, template)
.createAsync(ListTestComponent)
.then((fixture) => {
var items, visibleItems,
list = fixture.componentInstance.viewChild;
spyOn(list.filtering, 'emit');
spyOn(list.filtered, 'emit');
fixture.detectChanges();
items = list.items;
visibleItems = items.filter((listItem) => { return !listItem.hidden; });
expect(list.items.length).toBe(3);
expect(visibleItems.length).toBe(3);
list.searchInputElement = document.createElement('input');
list.searchInputElement.value = "3"; // filtering down only to item 3
fixture.componentInstance.filteringHandler = (args: any) => { args.cancel = true; }; // it should prevent form filtering
fixture.detectChanges();
list.filter(); // filter should not happen because of canceling
fixture.detectChanges();
visibleItems = items.filter((listItem) => { return !listItem.hidden; });
expect(visibleItems.length).toBe(3);
expect(list.filtering.emit).toHaveBeenCalledWith({ cancel: false });
expect(list.filtered.emit).not.toHaveBeenCalledWith({ result: [visibleItems[0]] });
}).catch (reason => {
console.log(reason);
return Promise.reject(reason);
});
})));
&#13;
然而,尽管我希望从测试中取消过滤,但它不会和过滤器发生。这导致测试意外结果,但失败了。 使用karma / jasmine测试同步发射器有什么问题?