12

Using Angular 7 I added material table to my application with ng generate @angular/material:table test-table

Inside the generated template there is a paginator:

<mat-paginator #paginator
    [length]="dataSource.data.length"
    [pageIndex]="0"
    [pageSize]="50"
    [pageSizeOptions]="[25, 50, 100, 250]">
</mat-paginator> 

On init the datasource is changed:

ngOnInit() {
  this.dataSource = new ItemsTableDataSource(
    this.paginator,
    this.sort,
    this.route.paramMap,
    this.afs
 );
}

When trying to compile the component on Karma expect(component).toBeTruthy(); I'm getting the following error

Error: ExpressionChangedAfterItHasBeenCheckedError: Expression has 
changed after it was checked. Previous value: 'length: 0'. Current 
value: 'length: 1'.

How can I solve this issue?

Gonçalo Peres
  • 11,752
  • 3
  • 54
  • 83
Roni Hacohen
  • 313
  • 5
  • 16

2 Answers2

19

Not sure how kosher it is but in my case I simply removed the 'fixture.detectChanges()' call from the spec file. I am working with an A6 ReactiveForm, setting some initial dummy date range values in the test. The form works fine but the test failed with your error.

EddieBaby
  • 272
  • 3
  • 4
  • 2
    On my hand we had 2 `fixture.detectChanges()` statement one the the `beforeEach` and one in `it` function callback. Removing the one in `it` function callback did the trick for me. – svassr Sep 14 '20 at 01:48
  • 1
    It worked for me but why? because some people say it should be called in beforeEach, while others say to never call it. – matttm Nov 02 '22 at 13:10
1

Understanding ExpressionChangedAfterItHasBeenCheckedError

Instead of removing the line and getting rid of error that could be a valuable hint, actually I suggest to watch the video from Angular documentation explaining what is the error trying to warn you about.

Angular helps to ensure that your component is stable after it was created. Stable means no values (properties) change when detectChanges() is run. It may be worth reviewing if there are any changes that you do in ngAfterViewInit or any function/properties returning different value with each call (like random)

Documentation links

Documentation: https://angular.io/errors/NG0100

Video (6 minutes): https://youtu.be/O47uUnJjbJc

Specific case of mat-table

Above is an explanation of the problem on general level. Specific case that the question refers to is explained here: https://stackoverflow.com/a/53015635/9226213

Krystian
  • 122
  • 1
  • 10