Angular paginator не связывается должным образом во время тестирования юнитов кармы - PullRequest
0 голосов
/ 30 апреля 2020

Я работал над созданием приложения Angular. Он состоит из таблицы с нумерацией страниц, сортировкой и фильтрацией. Все работает нормально, когда я запускаю ng serve, но разбиение на страницы не работает, когда я бегу ng test. Я хочу написать контрольные примеры для paginator, но datasource.paginator.length дает мне 0 даже при наличии источника данных, имеющего данные.

Ниже приведен снимок экрана, на котором paginator не связывается при выполнении теста.

Paginator не связывается

Ниже приведен мой фрагмент кода:

app.component.ts


  public weatherData : Array<CityWeather>;

  @ViewChild(GraphComponent) graphComponent : GraphComponent;

  /**
   * Table related variables
   */
  displayedColumns: string[] = ['id', 'city_name', 'country', 'temperature', 'feels_like', 'humidity', 'weather_description'];

  public dataSource : MatTableDataSource<any>;

  @ViewChild(MatSort, {static: true}) sort: MatSort;

  @ViewChild(MatPaginator, {static: true}) paginator: MatPaginator;

  constructor(private weatherService: WeatherService) {}

  ngOnInit() {
    this.weatherService.getWeather(cityIds)
      .subscribe(data => {
        this.weatherData = this.extractCityWeather(data);
        this.dataSource = new MatTableDataSource(this.weatherData);
        this.dataSource.sort = this.sort;
        this.dataSource.paginator = this.paginator;
      }
    );
  }

app.component.spe c .ts

describe('AppComponent', () => {
    let component: AppComponent;
    let fixture: ComponentFixture<AppComponent>;

    beforeEach(async(() => {
        TestBed.configureTestingModule({
            declarations: [
                AppComponent,
                GraphComponent
            ],
            imports: [
                BrowserModule,
                BrowserAnimationsModule,
                HttpClientModule,
                MaterialModule
            ],
            providers: [
                {
                    provide: WeatherService,
                    useClass: WeatherServiceMock
                },
                MatPaginator,
                MatSort
            ],
            schemas: [ NO_ERRORS_SCHEMA ]
        }).compileComponents();
    }));

    beforeEach(() => {
        fixture = TestBed.createComponent(AppComponent);
        component = fixture.componentInstance;
        component.graphComponent = new GraphComponentMock();
        component.ngOnInit();
        fixture.detectChanges();
    });

    it('should create the app', () => {
        expect(component).toBeTruthy();
    });

    it('should populate datasource', () => {
        expect(component.dataSource).not.toBeNull();
    })

    /**
    * Filtering test case
    */
    it('city filter should filter out 1 city', () => {
        component.applyFilter('cam');
        expect(component.dataSource.filteredData.length).toEqual(1);
    })

    it('city filter should not filter anything', () => {
        component.applyFilter('RANDOM_CITY_NAME_ALSKJDLASKJ');
        expect(component.dataSource.filteredData.length).toEqual(0);
    })

    it('pagination should work', () => {
        let i=1;
        while(component.dataSource.paginator.hasNextPage()) {
            i++;
            component.dataSource.paginator.nextPage();
        }
        expect(i).toEqual(4);
    })

});

@ViewChild(MatPaginator, {static: true}) paginator: MatPaginator здесь static:true используется, потому что, если он будет удален, мне придется высмеивать этот объект в тестовом прогоне. MatPaginator ожидает несколько аргументов как конструктор, который привел к другой проблеме.

Пожалуйста, помогите мне понять, почему нумерация страниц не работает. Заранее спасибо! :)

1 Ответ

0 голосов
/ 30 апреля 2020

Я изменил fixture.detectChanges(); на fixture.autoDetectChanges(); и все заработало.

...