gpt4 book ai didi

Angular Material 虚拟滚动不在单元测试中渲染项目

转载 作者:行者123 更新时间:2023-12-02 16:48:50 25 4
gpt4 key购买 nike

我在我的组件中使用cdk-virtual-scroll-viewport + cdkVirtualFor,它似乎工作正常。

但是在该组件的单元测试中,项目不会被渲染。

我制作了一个示例应用程序based on this example虽然该示例在您提供应用程序时有效,但我编写的测试失败了。

app.module.ts

import { ScrollingModule } from '@angular/cdk/scrolling';
import { BrowserModule } from '@angular/platform-browser';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { NgModule } from '@angular/core';

import { AppComponent } from './app.component';

@NgModule({
declarations: [
AppComponent,
],
imports: [
BrowserModule,
BrowserAnimationsModule,
ScrollingModule,
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }

app.component.ts

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

@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss'],
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class AppComponent {
items = Array.from({length: 100000}).map((_, i) => `Item #${i}`);
}

app.component.html

<cdk-virtual-scroll-viewport itemSize="50" class="example-viewport">
<div *cdkVirtualFor="let item of items" class="example-item">{{ item }}</div>
</cdk-virtual-scroll-viewport>

app.component.spec.ts

import { TestBed, async } from '@angular/core/testing';
import { AppComponent } from './app.component';
import { ScrollingModule } from '@angular/cdk/scrolling';

describe('AppComponent', () => {
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [
AppComponent
],
imports: [
ScrollingModule,
],
}).compileComponents();
}));

it('should render at least 4 items', () => {
const fixture = TestBed.createComponent(AppComponent);
fixture.detectChanges();
const compiled = fixture.debugElement.nativeElement as HTMLElement;
expect(compiled.querySelectorAll('.example-item').length).toBeGreaterThanOrEqual(4); // <-- Error: Expected 0 to be greater than or equal 4.
});
});

最佳答案

将单元测试(参见问题)更改为以下解决方案:

it('should render at least 4 items', fakeAsync(() => { // <---
const fixture = TestBed.createComponent(AppComponent);
fixture.autoDetectChanges(); // <---
tick(500); // <---
const compiled = fixture.debugElement.nativeElement as HTMLElement;
expect(compiled.querySelectorAll('.example-item').length).toBeGreaterThanOrEqual(4);
}));

关于Angular Material 虚拟滚动不在单元测试中渲染项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53726484/

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