如何模拟“CdkVirtualScrollViewport”以在 Angular 中无限滚动?

问题描述 投票:0回答:2
 @ViewChild('scroller')
  scroller!: CdkVirtualScrollViewport;

  constructor(private ngZone: NgZone) { }

  ngAfterViewInit(): void {
    this.unsub = this.scroller.elementScrolled().pipe(
      map(() => this.scroller.measureScrollOffset('bottom')),
      pairwise(),
      filter(([y1, y2]) => (y2 < y1 && y2 < 140)),
      throttleTime(200)
    ).subscribe(() => {
      this.ngZone.run(() => {
        (this.maxItems > this.listItems.length) && this.fetchMore();
      });
    })
  }
<cdk-virtual-scroll-viewport class="example-viewport" #scroller itemSize="72">
  <table mat-table [dataSource]="dataSource" class="mat-elevation-z8">

    <ng-container matColumnDef="name">
      <th mat-header-cell *matHeaderCellDef> Name </th>
      <td mat-cell *matCellDef="let element"> {{element.name}} </td>
    </ng-container>
  
    <ng-container matColumnDef="symbol">
      <th mat-header-cell *matHeaderCellDef> Symbol </th>
      <td mat-cell *matCellDef="let element"> {{element.symbol}} </td>
    </ng-container>
  
    <tr mat-header-row *matHeaderRowDef="displayedColumns; sticky: true"></tr>
    <tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>

  </table>
</cdk-virtual-scroll-viewport>

测试用例:

  it('should check \'ngAfterViewInit\'', () => {
    component.ngAfterViewInit();
    changeDetectorRef.detectChanges();
    spyOn(virtualScrollViewport, 'elementScrolled').and.callThrough();
    expect(virtualScrollViewport.elementScrolled).toHaveBeenCalled();
  });

错误跟踪我在模拟时得到的信息

        Error: Error: cdk-virtual-scroll-viewport requires the "itemSize" property to be set.
            at new CdkVirtualScrollViewport (http://localhost:9876/_karma_webpack_/node_modules/@angular/cdk/__ivy_ngcc__/fesm2015/scrolling.js:1264:1)
            at new MockCdkVirtualScrollViewport (http://localhost:9876/_karma_webpack_/main.js:27773:9)
            at Object.factory (http://localhost:9876/_karma_webpack_/node_modules/@angular/core/__ivy_ngcc__/fesm2015/core.js:17371:1)
            at R3Injector.hydrate (http://localhost:9876/_karma_webpack_/node_modules/@angular/core/__ivy_ngcc__/fesm2015/core.js:17247:42)
            at R3Injector.get (http://localhost:9876/_karma_webpack_/node_modules/@angular/core/__ivy_ngcc__/fesm2015/core.js:16997:1)
            at NgModuleRef$1.get (http://localhost:9876/_karma_webpack_/node_modules/@angular/core/__ivy_ngcc__/fesm2015/core.js:36383:1)
            at TestBedRender3.inject (http://localhost:9876/_karma_webpack_/node_modules/@angular/core/__ivy_ngcc__/fesm2015/testing.js:3227:1)
            at Function.inject (http://localhost:9876/_karma_webpack_/node_modules/@angular/core/__ivy_ngcc__/fesm2015/testing.js:3110:1)
            at UserContext.<anonymous> (http://localhost:9876/_karma_webpack_/src/app/components/gridview/gridview.component.spec.ts:112:37)
angular unit-testing angular-material karma-jasmine angular-cdk-virtual-scroll
2个回答
1
投票

模拟类的可能实现可能是这样的:

import { CdkVirtualScrollViewport } from '@angular/cdk/scrolling';
import { Subject } from 'rxjs';

export class MockCdkVirtualScrollViewport implements CdkVirtualScrollViewport {
  scrolledIndexChange: Subject<number> = new Subject<number>();
  elementScrolled: Subject<Event> = new Subject<Event>();
  setRenderedRange(): void { }
  getRenderedRange(): any { }
  // add any other properties and methods that are needed for your test
}

您可以像这样在测试中使用它:

import { ComponentFixture, TestBed } from '@angular/core/testing';
import { Component } from '@angular/core';
import { CdkVirtualScrollViewport } from '@angular/cdk/scrolling';
import { MockCdkVirtualScrollViewport } from './mock-cdk-virtual-scroll-viewport';

describe('YourComponent', () => {
  let component: YourComponent;
  let fixture: ComponentFixture<YourComponent>;
  let virtualScrollViewport: CdkVirtualScrollViewport;

  beforeEach(async () => {
    // configure the test module with the mock class
    await TestBed.configureTestingModule({
      declarations: [ YourComponent ],
      providers: [
        { provide: CdkVirtualScrollViewport, useClass: MockCdkVirtualScrollViewport }
      ]
    }).compileComponents();

    // create an instance of the component and the mock class
    fixture = TestBed.createComponent(YourComponent);
    component = fixture.componentInstance;
    virtualScrollViewport = TestBed.inject(CdkVirtualScrollViewport);
  });

  it('should do something', () => {
    // use the methods and properties of the mock class in your test
    // for example you can call the `setRenderedRange()` method and check that it works as expected
  });
});

0
投票

我有同样的问题。最初将

CdkVirtualScrollViewport
添加到提供者列表中,无论有没有模拟,它都要求设置“itemSize”。

最后从提供者列表中删除

CdkVirtualScrollViewport
,然后将
ScrollingModule
添加到导入列表中。只是单行。

© www.soinside.com 2019 - 2024. All rights reserved.