0
votes

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 wich 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
});
1
I have edit the post - gad
By the way, does it work properly and only the test fails? I mean it renders when you local debug your application? - Kristóf Tóth

1 Answers

0
votes

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.)