Angular 角度jasmine测试无法触发使用fromEvent rxjs运算符创建的可观测值

Angular 角度jasmine测试无法触发使用fromEvent rxjs运算符创建的可观测值,angular,jasmine,rxjs,angular-test,Angular,Jasmine,Rxjs,Angular Test,我有一个简单的例子。角度应用程序的标准AppComponent包含一个ChildComponent,该组件在其自己的模块ChildModule中定义 ChildComponent的模板非常简单 <div class="child" (click)="testClick($event)"></div> 现在我想在AppComponent上构建一个测试,模拟点击ChildComponent 这是测试的代码 describe('AppComponent', () =>

我有一个简单的例子。角度应用程序的标准
AppComponent
包含一个
ChildComponent
,该组件在其自己的模块
ChildModule
中定义

ChildComponent
的模板非常简单

<div class="child" (click)="testClick($event)"></div>
现在我想在
AppComponent
上构建一个测试,模拟点击
ChildComponent

这是测试的代码

describe('AppComponent', () => {
  let fixture: ComponentFixture<AppComponent>;
  let app: AppComponent;
  let child: DebugElement;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [ ChildModule ],
      declarations: [
        AppComponent
      ],
    }).compileComponents();
  }));
  beforeEach(() => {
    fixture = TestBed.createComponent(AppComponent);
    app = fixture.debugElement.componentInstance;
    child = fixture.debugElement.query(By.css('.child'));
    fixture.detectChanges();
  });

  it(`should create the child'`, async(() => {
    expect(child).toBeTruthy();
  }));

  it(`clicks on the child and the relative Observable emits`, async(() => {
    setTimeout(() => {
      child.triggerEventHandler('click', 'clicked');
    }, 100);

  }));

});
我用
ng serve
启动开发服务器,我看到控制台上打印了两条消息,一条是通过
testClick
方法打印的,另一条是通过订阅
testClick$
可观察的

如果我现在运行与以前相同的测试,我希望在控制台上也能看到相同的两条消息。相反,我只看到通过
testClick
方法打印的消息。订阅的消息,即
'test click in child'
,没有出现,这意味着可观察的
testClick$
child.triggerEventHandler('click','clicked')时不会发出被执行


如何使使用
fromEvent
创建的可观察对象在jasmine测试中工作?我做错了什么?

最终我找到了一种触发事件的方法,可以在RxJs的
fromEvent
函数中使用

这一解决方案受到了以下因素的启发

其思想是,为了能够从DOM事件创建事件流,必须在DebugElement包装的本机元素上使用方法
dispatchEvent

所以,与其做

child.triggerEventHandler('click', 'clicked');
你必须使用类似于

child.nativeElement.dispatchEvent(new MouseEvent('click', {...});
child.triggerEventHandler('click', 'clicked');
child.nativeElement.dispatchEvent(new MouseEvent('click', {...});