angular - 单元测试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');
});
}));
});
解决方案
我可以简单地使用以下方法触发滚动事件:
page.myElement.dispatchEvent(new Event('scroll'));
鉴于我page.myElement
的链接到我的 HTML 元素
<div id='my-element' (scroll)="onScroll()">
这是一种更好的方法,而不是直接component.onScroll()
从单元测试中调用。
推荐阅读
- python - 我需要使用 np.where 函数为变量设置条件
- mysql - Mysql通过连接从表中获取数据
- android - Android Camera 2 API 镜头切换
- css - 为什么我在规则 @use 中不断获得 Uknown?
- reactjs - React - 显示帖子详细信息
- reactjs - Storyshots - 无法读取 null 的属性“scrollWidth”
- python - Python web-scraping with login on button
- angular - Angular 8“TypeError:无法读取未定义的属性'长度'”
- c# - 如何通过引用访问索引器
- jenkins - 带有 ansicolor 的 otput 中的 Jenkins 错误 script.sh