Antflow
Antflow

Reputation: 73

Angular unit test with @ContentChild fails

I have a custom menu close on the Angular Material menu component and I want to test that, but it keeps failing and outputs "TypeError: Cannot read property 'closeMenu' of undefined"

Spec file (test at the bottom):

@Component({
  selector: 'app-test',
  template: `
    <app-header-menu>
      <button [matMenuTriggerFor]="test">Test</button>
      <mat-menu #test="matMenu">menu content</mat-menu>
    </app-header-menu>
  `
})
class TestComponent {}

describe('HeaderMenuComponent', () => {
  let component: TestComponent;
  let fixture: ComponentFixture<TestComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ TestComponent, HeaderMenuComponent ],
      imports: [
        MatMenuModule
      ]
    })
    .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(TestComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it ('should close on click', () => {
    document.dispatchEvent(new MouseEvent('click'));
    expect(fixture.debugElement.query(By.css('app-header-menu')).nativeElement.trigger.closeMenu()).toHaveBeenCalled();
  });
});

Component file:

export class HeaderMenuComponent {
  @ContentChild(MatMenuTrigger) trigger: MatMenuTrigger;

  @HostListener('document:click', ['$event'])
  onClick = event => {
    if (this.trigger && this.trigger.menuOpen && !this.elRef.nativeElement.contains(event.target)) {
      this.trigger.closeMenu();
    }
  }
}

Anybody got a clue what I'm doing wrong?

Upvotes: 2

Views: 2255

Answers (1)

Erbsenkoenig
Erbsenkoenig

Reputation: 1659

Using the wrapper component is the right way to go, if you want to test your @ContentChild(ren).

The thing is though, that to test the trigger to be closed, you need to open it first before actually triggering a click event on the document.

PFB my test setup and the test itself. What I haven't found out is why the mat-menu is not opened once the button is clicked. I triggered the openMenu directly using the content child.

In a sense, imho there is no need to test the angular material functionallity, so triggering the menu directly should be fine for your test case anyway.

What I did differently to your test setup, I used the componentInstance from the component having the MatMenuTrigger, since a native HtmlElement doesn't have a trigger nor the closeMenu method to spy on.

Here is a stackblitz:


component.spec.ts

@Component({
    selector: 'test-cmp',
    template: `<app-component>
        <button [matMenuTriggerFor]="test">Test</button>
        <mat-menu #test="matMenu">menu content</mat-menu>
    </app-component>`,
  })
  class TestWrapperComponent { }


describe('AppComponent', () => {
    let component: AppComponent;
    let fixture: ComponentFixture<TestWrapperComponent>;

    beforeEach(async(() => {
        TestBed.configureTestingModule({
            declarations: [AppComponent, TestWrapperComponent],
            providers: [],
            imports: [MatMenuModule, BrowserAnimationsModule],
            schemas: []
        })
            .compileComponents();
    }));

    beforeEach(() => {
        fixture = TestBed.createComponent(TestWrapperComponent);
        component = fixture.debugElement.children[0].componentInstance;
    });

    it('should be created', () => {
      fixture.detectChanges();
      expect(component).toBeTruthy();
    });

    it ('should close on click', fakeAsync(() => {
    fixture.detectChanges();
    const closeMenueSpy: jasmine.Spy = spyOn(component.trigger, 'closeMenu');

    // Not too sure why this menu doesn't open on click
    // const debugElem: DebugElement = fixture.debugElement.query(By.css('button'));
    // debugElem.triggerEventHandler('click', null);
    component.trigger.openMenu();
    tick();

    expect(component.trigger.menuOpen).toBeTruthy();

    document.dispatchEvent(new MouseEvent('click'));
    tick();

    expect(closeMenueSpy).toHaveBeenCalled();
  }));
});

Upvotes: 3

Related Questions