单元测试 Angular 5 滚动事件在 whenStable 之后触发



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

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

App.Component.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');
}
}

应用组件.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>

应用组件.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');
});
}));
});

我能够简单地使用以下命令触发滚动事件:

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

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

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

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

事实证明我需要使用该行

container.triggerEventHandler('scroll', null); 

而不是

container.nativeElement.scroll(); 

相关内容

最新更新