【问题标题】:Angular jasmine test not able to trigger Observable created with fromEvent rxjs operatorAngular jasmine 测试无法触发使用 fromEvent rxjs 运算符创建的 Observable
【发布时间】:2018-12-29 23:56:39
【问题描述】:

我有一个简单的案例。 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。我想使用fromEvent 运算符和ViewChildclick 事件上创建一个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',没有出现,这意味着当child.triggerEventHandler('click', 'clicked');被执行时,ObservabletestClick$没有发出。

如何使使用fromEvent 创建的 Observables 在 jasmine 测试中工作?我做错了什么?

【问题讨论】:

    标签: angular jasmine rxjs angular-test


    【解决方案1】:

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

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

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

    所以,与其做

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

    你必须使用类似的东西

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-07-07
      • 1970-01-01
      • 2017-08-17
      • 1970-01-01
      • 2020-12-12
      • 1970-01-01
      • 2019-03-29
      相关资源
      最近更新 更多