gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 16:05:21 26 4
gpt4 key购买 nike

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

我尝试使用 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');
}
}

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()

关于angular - 单元测试Angular 5滚动事件在whenStable之后触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50264090/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com