首页 > 解决方案 > 单元测试Angular 5滚动事件在whenStable之后触发

问题描述

我一直无法找出为什么这个测试不起作用。给定我下面的示例代码。当我对滚动组件中的子 DIV 元素时所做的更改进行单元测试时。事件处理程序按预期触发,但 async\whenStable 不等待 Zone 任务完成,任务在测试完成时触发。

我尝试使用 Renderer2.listen 分配事件,结果完全相同。

应用组件.ts

import { Component, Renderer2, ViewChild } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  @ViewChild('message') messageBox: HTMLDivElement;
  constructor(private renderer: Renderer2) {}

  onScroll() {
     this.renderer.setStyle(this.messageBox, 'color', 'blue');
  }
}

App.Component.html

<div class="scrollWindow" (scroll)="onScroll($event)">
  <div class="scrollContent">Bacon ipsum dolor amet short ribs jowl ball tip turkey sirloin meatloaf ground round capicola pork belly pork chop doner
    flank brisket boudin. Pork chop sausage alcatra meatloaf pork belly meatball bacon tongue tenderloin pastrami hamburger
    pork ribeye andouille biltong. Doner bresaola biltong chicken cupim ham. Beef ribs drumstick ground round bresaola prosciutto
    andouille, pork belly beef flank. Bacon beef cupim turkey, buffalo sausage ham tongue rump ground round doner swine pastrami
    chuck.
  </div>
</div>
<p #message>This is a message</p>

App.Component.css

.scrollWindow {
  position: relative;
  width: 100px;
  height: 100px;
  overflow: auto;
}

.scrollContent {
  position: relative;
  width: 200px;
  height: 200px;
  background-color: aquamarine;
}

App.Component.spec.ts

import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { AppComponent } from './app.component';
import { By } from '@angular/platform-browser';

describe('AppComponent', () => {
  let component: AppComponent;
  let fixture: ComponentFixture<AppComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [AppComponent]
    }).compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(AppComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create the app', async(() => {
    const container = fixture.debugElement.query(By.css('.scrollWindow'));

    container.nativeElement.scrollLeft = 50;
    expect(container.nativeElement.scrollLeft).toEqual(50);

    container.nativeElement.scroll();
    fixture.detectChanges();

    fixture.whenStable().then(() => {
      const message = fixture.debugElement.query(By.css('p'));
      expect(message.styles.color).toEqual('blue');
    });
  }));
});

标签: angularunit-testingscrolldom-events

解决方案


我可以简单地使用以下方法触发滚动事件:

page.myElement.dispatchEvent(new Event('scroll'));

鉴于我page.myElement的链接到我的 HTML 元素

<div id='my-element' (scroll)="onScroll()">

这是一种更好的方法,而不是直接component.onScroll()从单元测试中调用。


推荐阅读