From c90dcfb5acf91e16fdb4f6f167d0b3bc90a4f4c7 Mon Sep 17 00:00:00 2001 From: Kristiyan Kostadinov Date: Tue, 21 Aug 2018 20:44:33 +0200 Subject: [PATCH] fix(menu): throw better error when trying to open undefined menu (#12688) Throws a better error than "Unable to read property templateRef of undefined" when clicking on a trigger with an undefined menu. We have a check for this already in one of the lifecycle hooks, but people can skip it when unit testing. Fixes #12649. --- src/lib/menu/menu-trigger.ts | 2 ++ src/lib/menu/menu.spec.ts | 13 +++++++++++++ 2 files changed, 15 insertions(+) diff --git a/src/lib/menu/menu-trigger.ts b/src/lib/menu/menu-trigger.ts index b2895608564a..aa7349761a2d 100644 --- a/src/lib/menu/menu-trigger.ts +++ b/src/lib/menu/menu-trigger.ts @@ -195,6 +195,8 @@ export class MatMenuTrigger implements AfterContentInit, OnDestroy { return; } + this._checkMenu(); + const overlayRef = this._createOverlay(); this._setPosition(overlayRef.getConfig().positionStrategy as FlexibleConnectedPositionStrategy); overlayRef.attach(this._portal); diff --git a/src/lib/menu/menu.spec.ts b/src/lib/menu/menu.spec.ts index c4bcae34397f..4b10cf88d178 100644 --- a/src/lib/menu/menu.spec.ts +++ b/src/lib/menu/menu.spec.ts @@ -427,6 +427,19 @@ describe('MatMenu', () => { expect(triggerEl.hasAttribute('aria-expanded')).toBe(false); }); + it('should throw the correct error if the menu is not defined after init', () => { + const fixture = createComponent(SimpleMenu, [], [FakeIcon]); + fixture.detectChanges(); + + fixture.componentInstance.trigger.menu = null!; + fixture.detectChanges(); + + expect(() => { + fixture.componentInstance.trigger.openMenu(); + fixture.detectChanges(); + }).toThrowError(/must pass in an mat-menu instance/); + }); + describe('lazy rendering', () => { it('should be able to render the menu content lazily', fakeAsync(() => { const fixture = createComponent(SimpleLazyMenu);