0

I have a component that render a table using Angular Material mat-table. It is working fine, but in my spec file the table does not render the elements of the body (tds and trs), so the test fails. It seems that I initialize the text correct, I import the MatTableModule, and also initialize the datasource for the mat-table.

The component get input which goes to the datasource, it not async, and I call fixture.detectChanges() after initializing the input.

The table and body tags are rendered but the body tag is empty. Any suggestions why the data of the table is not rendered?

Thanks

here is a sample of the test code:

let component: MyComponent;
let fixture: ComponentFixture<MyComponent>;
const dataSource: DataSource[] = [{id: 1, name: 'a'}];

beforeEach(async(() => {
    TestBed.configureTestingModule({
        declarations:[MyComponent],
        imports: [MatTableModule],
}));

beforeEach(() => {
    fixture = TestBed.createComponent(MyComponent);
    component = fixture.componentInstance;
    debugElement = fixture.debugElement
});

it('should display results', () => {
    component.myDataSource = dataSource;
    fixture.detectChanges();
    
    console.log(debugElement.nativeElement); //here I see that the body is empty

    const elements = debugElement.queryAll(By.css('td'));
    expect(elements.length).toBe(2); // I get 0
});
Jason Aller
  • 3,541
  • 28
  • 38
  • 38
gad
  • 11
  • 1
  • 3

1 Answers1

0

Try importing MatTableDataSource, declaring table containing array of object, initializing with new MatTableDataSource<type>(array) and don't forget to check the column definitions, because the table doesn't render if the definitions cause an error (e.g. it doesn't find some column etc.)

Roy
  • 7,811
  • 4
  • 24
  • 47
Kristóf Tóth
  • 791
  • 4
  • 19