I have a mat-menu in which content may differ regarding user. I try to write unit test but from what I see, jasmine doesn't see the CDK div
, so I cannot grab menu entries.
My template:
<button id="account" mat-icon-button [matMenuTriggerFor]="menu" aria-label="Profile">
<mat-icon>person</mat-icon>
</button>
<mat-menu #menu="matMenu">
<button mat-menu-item *ngxPermissionsOnly="PERMISSION.USER_LIST" id="user-list" (click)="usersList()">
<mat-icon>recent_actors</mat-icon>
</button>
<button mat-menu-item *ngxPermissionsOnly="PERMISSION.INFORMATIONS" id="informations" (click)="infoList()">
<mat-icon>info</mat-icon>
</button>
<button mat-menu-item id="logout" (click)="logout()">
<mat-icon>exit_to_app</mat-icon>
</button>
</mat-menu>
The unit test:
let component: HeaderComponent;
let fixture: ComponentFixture < HeaderComponent > ;
const providers: any[] = headerProviders;
beforeEach(async (() => {
TestBed.configureTestingModule({
declarations: [
HeaderComponent,
NgxPermissionsRestrictStubDirective
],
providers: providers,
imports: [
BrowserAnimationsModule,
BrowserModule,
CommonModule,
CommonSogetrelModule,
FlexLayoutModule,
SharedMaterialModule,
RouterTestingModule.withRoutes([])
]
})
.compileComponents()
.then(() => {
fixture = TestBed.createComponent(HeaderComponent);
component = fixture.componentInstance;
});
}));
it('should not display elements which needs permissions', () => {
fixture.nativeElement.querySelector('#account').click();
fixture.detectChanges();
expect(logoutBtn).toBeTruthy('Le bouton Déconnexion doit être affiché');
expect(fixture.debugElement.nativeElement.querySelector('#user-list')).toBeFalsy();
});
I've tried with
console.info(fixture.nativeElement.parentNode);
const menu = fixture.nativeElement.parentNode.querySelector('.mat-menu-panel');
expect(menu).toBeTruthy();
What I can see with the console.info
is that there's no CDK div
on the page, and so obviously the .mat-menu-panel
isn't found.
Any idea about how to test the mat-menu content?
MatMenuModule
andMatIconModule
in yourimports
array. You most likely have it since you are not getting errors for compiling. – Peeplesfixture.debugElement.query(By.css('#account')).nativeElement.click()
andexpect(fixture.debugElement.query(By.css('#logout'))).toBeTruthy()
,expect(fixture.debugElement.query(By.css('#user-list'))).toBeFalsy()
?, still I think you should add whatever the console output is, or the output of the test, actually both. – Baez