-
Notifications
You must be signed in to change notification settings - Fork 44
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
I can't test the rendered rows in the table. #103
Comments
Hi! |
Hi, I'm actually having the same problem. I've tried to set the height of the viewport container and also some suggestions found here https://stackoverflow.com/questions/53726484/angular-material-virtual-scroll-not-rendering-items-in-unit-tests but nothing seems to work. html: <cdk-virtual-scroll-viewport
</table_> code: export interface PeriodicElement { const ELEMENT_DATA: PeriodicElement[] = [...Array(1000).keys()].map((i) => ({ @component({ constructor() {} ngOnInit(): void { spec: describe('TestTableComponent', () => { const finishInit = () => {
}; beforeEach(async () => {
}); it('should create', () => { it('should render rows', fakeAsync(() => {
})); In the test, no rows are rendered. The "No record found" label is shown all the time. |
I found a trick that is working to render (at least some) rows while testing. This at least works for angular applications (I use Angular 12 as for now). In your // Ensure that the cdk-virtual-scroll-viewport is not fully squashed so that at least one row is rendered
beforeAll(() => {
const styleElement = document.createElement('style');
// Adjust min-width and min-height to display the amount of items you need (with 100px, at least one row should be shown)
styleElement.textContent = 'cdk-virtual-scroll-viewport { min-width: 100px !important; min-height: 100px !important; }';
styleElement.id = 'custom-test-style-virtual-scroll-viewport';
document.head.append(styleElement);
}); This adds an extra style when testing. It ensures that the Note that I use For reference, this is my full // This file is required by karma.conf.js and loads recursively all the .spec and framework files
// @formatter:off
import 'zone.js/dist/zone-testing'; // Keep this first otherwise tests will fail (https://stackoverflow.com/questions/67414283/error-zone-testing-js-is-needed-for-the-fakeasync-test-helper-but-could-not-b/70000591#70000591)
import { getTestBed } from '@angular/core/testing';
import { BrowserDynamicTestingModule, platformBrowserDynamicTesting } from '@angular/platform-browser-dynamic/testing';
// @formatter:on
declare const require: {
context(
path: string,
deep?: boolean,
filter?: RegExp
): {
keys(): string[];
<T>(id: string): T;
};
};
// Ensure that the cdk-virtual-scroll-viewport is not fully squashed so that at least one row is rendered
beforeAll(() => {
const styleElement = document.createElement('style');
// Adjust min-width and min-height to display the amount of items you need (with 100px, at least one row should be shown)
styleElement.textContent = 'cdk-virtual-scroll-viewport { min-width: 100px !important; min-height: 100px !important; }';
styleElement.id = 'custom-test-style-virtual-scroll-viewport';
document.head.append(styleElement);
});
// First, initialize the Angular testing environment.
getTestBed().initTestEnvironment(BrowserDynamicTestingModule, platformBrowserDynamicTesting());
// Then we find all the tests.
const context = require.context('./', true, /\.spec\.ts$/);
// And load the modules.
context.keys().map(context); Hope this helps. |
Hi Damien. Thanks for your suggestion. I've tried it out but without any success. There are still no rows rendered in my case. It seems to me that the height of the table is not set and that could be the issue. |
Things you can try is to set the Also, maybe try with the following setup CSS style:
I had this as working global setup for tests before removing beforeAll(() => {
const styleElement = document.createElement('style');
// Container of the tested component (A <div></div> with an id start starts with 'root'):
// - Set width to 500px x 500px
// This is particularly required for tables/grids that uses virtualization for their items.
// See: https://github.com/diprokon/ng-table-virtual-scroll/issues/103
// - Make it transparent and set overflow to scroll so that it does not screw up the test results display
styleElement.textContent = 'div[id^=root] { width: 500px !important; height: 500px !important; overflow: scroll; opacity: 0; }';
styleElement.id = 'custom-test-style-virtual-scroll-viewport';
document.head.append(styleElement);
}); In the end, I had to find a style that ensured the size of the I really hope you find a solution. This has haunted me quite a bit. |
I try to run my unit tests with jest to check rendered rows in my table but no row are rendered.
this is test in my spec.ts file:
describe('ProjectsTableComponent', () => {
let component: ProjectsTableComponent;
let fixture: ComponentFixture;
const testProjects: Project[] | null = [array containing two project];
beforeEach(
waitForAsync(() => {
TestBed.configureTestingModule({
imports: [
CommonModule,
BrowserModule,
BrowserAnimationsModule,
MaterialModule,
],
declarations: [ProjectsTableComponent, BusinessUnitsBarComponent],
}).compileComponents();
})
);
beforeEach(() => {
fixture = TestBed.createComponent(ProjectsTableComponent);
component = fixture.componentInstance;
});
it('should create', () => {
expect(component).toBeTruthy();
});
it('projects input should populate table', fakeAsync(() => {
finishInit(fixture);
component.projects = testProjects;
fixture.detectChanges();
flush();
const compiled = fixture.debugElement.nativeElement;
expect(compiled.querySelectorAll('.mat-row').length).toBeGreaterThanOrEqual(
2
);
}));
});
/** Finish initializing the virtual scroll component at the beginning of a test. */
function finishInit(fixture: ComponentFixture) {
// On the first cycle we render and measure the viewport.
fixture.detectChanges();
flush();
// On the second cycle we render the items.
fixture.detectChanges();
flush();
// Flush the initial fake scroll event.
animationFrameScheduler.flush();
flush();
fixture.detectChanges();
}
my component.html
my component.ts
export class ProjectsTableComponent implements OnInit {
columns!: TableColumn[];
displayedColumns!: string[];
dataSource = new TableVirtualScrollDataSource();
private sort!: MatSort;
noDataMessage = MatTableConstants.noDataMessage;
@ViewChild(MatSort, { static: false }) set matSort(ms: MatSort) {
this.sort = ms;
this.setDataSourceAttributes();
}
@input() set projects(val: Project[] | null) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
this.dataSource.data = val as any;
}
@output() selectedProject = new EventEmitter();
constructor() {}
ngOnInit(): void {
this.columns = [
{
fieldName: 'projectNumber',
label: 'Project Number',
},
];
this.displayedColumns = this.columns.map((x) => x.fieldName);
}
getColumnLabel(fieldName: string): string | null {
return this.columns.find((x) => x.fieldName === fieldName)?.label || null;
}
private setDataSourceAttributes() {
this.dataSource.sort = this.sort;
this.dataSource.sortingDataAccessor = MatTableConstants.pathDataAccessor;
}
}
The text was updated successfully, but these errors were encountered: