I'm trying to write a test for my mat-menu
in my application's toolbar. When I call button.click()
in my test, I get a Cannot read property 'templateRef' of undefined
error in the console.
As all works find in the browser, I believe this is to do with how I am running the test?
app.component.spec.ts
import { TestBed, async, ComponentFixture } from '@angular/core/testing';
import { AppComponent } from './app.component';
import { RouterTestingModule } from '@angular/router/testing';
import { AppRoutes } from './app.routes';
import {
MatToolbarModule,
MatIconModule,
MatMenuModule,
MatButtonModule
} from '@angular/material';
import { HomeComponent } from './home/home.component';
import { UserService } from './user/user.service';
class MockUserService {
signIn() {}
}
describe('AppComponent', () => {
let app: AppComponent;
let fixture: ComponentFixture<AppComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [AppComponent, HomeComponent],
providers: [{ provide: UserService, useClass: MockUserService }],
imports: [
MatIconModule,
MatToolbarModule,
MatMenuModule,
MatButtonModule,
RouterTestingModule.withRoutes(AppRoutes)
]
}).compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(AppComponent);
app = fixture.debugElement.componentInstance;
});
it('should create the app', async(() => {
expect(app).toBeTruthy();
}));
it('open the menu when clicking on the account button', async () => {
const dom = fixture.debugElement.nativeElement;
const button = dom.querySelector('#userMenu');
button.click(); //Error occurs on this line, before the console.log()
console.log(button);
fixture.detectChanges();
});
});
app.component.html
<mat-menu #menu="matMenu" [overlapTrigger]="false" yPosition="below"> //appears to not be able to find this element?
<button mat-menu-item>
<span>Settings</span>
</button>
<button id="userSignIn" (click)="user.signIn()" mat-menu-item>
<span>Log In</span>
</button>
</mat-menu>
<mat-toolbar color="primary">
<span>Report Receiver</span>
<span class="fill-remaining-space"></span>
<button *ngIf="user.signedIn$ | async" routerLink="/emails/mapping" mat-icon-button>
<mat-icon>check_box</mat-icon>
</button>
<button *ngIf="user.signedIn$ | async" routerLink="/emails/received" mat-icon-button>
<mat-icon>list</mat-icon>
</button>
<button routerLink="/home" mat-icon-button>
<mat-icon>home</mat-icon>
</button>
<button id="userMenu" [matMenuTriggerFor]="menu" mat-icon-button>
<mat-icon>account_circle</mat-icon>
</button>
</mat-toolbar>
<router-outlet></router-outlet>