Angular 角度6,如何在子组件上测试父发射器?
我有一个选项卡组件作为其子组件的包装器,包装器组件发出每个选项卡的状态(打开或关闭)和索引,在每个子组件上我注入包装器组件以访问发射器 因此,基本上我正在尝试从我的子组件测试文件中的包装器组件订阅发射器:Angular 角度6,如何在子组件上测试父发射器?,angular,unit-testing,jasmine,subscription,eventemitter,Angular,Unit Testing,Jasmine,Subscription,Eventemitter,我有一个选项卡组件作为其子组件的包装器,包装器组件发出每个选项卡的状态(打开或关闭)和索引,在每个子组件上我注入包装器组件以访问发射器 因此,基本上我正在尝试从我的子组件测试文件中的包装器组件订阅发射器: it(`it should have a 'toggle()' function that close/open the tab and then emits the tab status`, (emitted) => { fixture = TestBed.createCom
it(`it should have a 'toggle()' function that close/open the tab and then emits the tab status`, (emitted) => {
fixture = TestBed.createComponent(AccordionTabComponent);
const compiled = fixture.componentInstance;
compiled.toggle(); // -> toggle function trigger the emit
const data = {
tabIndex: compiled.tabIndex,
isOpen: compiled.isOpen
}; // -> I get the current data from the child component to compare it with the emitted data.
compiled.accordionRef.open.subscribe(tabEmmited => {
console.log('tabEmmited: ', tabEmmited);
expect(JSON.stringify(data)).toBe(JSON.stringify(tabEmmited));
emitted();
});
fixture.detectChanges();
});
但看起来订阅从未发生,因为“订阅”中的“日志”从未打印任何内容,这也会导致此错误:
Error: Timeout - Async callback was not invoked within timeout specified by jasmine.DEFAULT_TIMEOUT_INTERVAL.
以下是我的组件中的一些代码,以获取更多上下文信息:
包装器组件:
export class AccordionComponent implements OnInit {
@ContentChildren(forwardRef(() => AccordionTabComponent)) public childrenTabs: QueryList<AccordionTabComponent>;
@Output() open: EventEmitter<{}> = new EventEmitter(); // -> Parent emitter.
}
您应该在代码实际发出事件发射器之前订阅它。这样你就不会错过这次活动
it(`it should have a 'toggle()' function that close/open the tab and then emits the tab status`, (emitted) => {
fixture = TestBed.createComponent(AccordionTabComponent);
const compiled = fixture.componentInstance;
//subscribe before emitting
compiled.accordionRef.open.subscribe(tabEmmited => {
expect(JSON.stringify(data)).toBe(JSON.stringify(tabEmmited));
});
compiled.toggle(); // -> Call the method that actually emits it
..........
fixture.detectChanges();
});
在订阅发射器之前发射。因此,当您订阅时,事件已经发出。谢谢,测试现在运行得很好。是否可以尝试先订阅,然后再切换?
it(`it should have a 'toggle()' function that close/open the tab and then emits the tab status`, (emitted) => {
fixture = TestBed.createComponent(AccordionTabComponent);
const compiled = fixture.componentInstance;
//subscribe before emitting
compiled.accordionRef.open.subscribe(tabEmmited => {
expect(JSON.stringify(data)).toBe(JSON.stringify(tabEmmited));
});
compiled.toggle(); // -> Call the method that actually emits it
..........
fixture.detectChanges();
});