Angular茉莉花测试无法触发使用fromEvent rxjs运算符创建的Observable

时间:2018-07-22 08:43:14

标签: angular jasmine rxjs angular-test

我有一个简单的案例。 Angular应用程序的标准AppComponent包含一个ChildComponent,它是在其自己的模块ChildModule中定义的。

ChildComponent的模板非常简单

<div class="child" (click)="testClick($event)"></div>

ChildComponent有一个甚至更简单的testClick(event)方法,它仅在控制台上记录一条消息。

testClick(event) {
    console.log(event);
}

现在,我想在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);

  }));

});

测试正常进行,特别是第二个测试按预期在控制台上显示clicked消息。

现在,我将ChildComponent复杂化了一点。我想使用click运算符和fromEventViewChild事件上创建一个Observable。

所以代码变成了

export class ChildComponent implements AfterViewInit {
  @ViewChild('child') private childElement: ElementRef;

  ngAfterViewInit() {
    const testClick$ = fromEvent(this.childElement.nativeElement, 'click');
    testClick$.subscribe(d => console.log('test click in child', d));
  }
}

我用ng serve启动开发服务器,并且看到控制台上打印了2条消息,一条消息是通过testClick方法发出的,一条消息是通过订阅testClick$ Observable来结束的。

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

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

1 个答案:

答案 0 :(得分:3)

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

该解决方案的灵感来自this post

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

所以,而不是做

child.triggerEventHandler('click', 'clicked');

您必须使用类似的东西

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