I recently created an Angular test to verify that the event method is being called. In the code snippet below, you can see that the onDialogClicked function takes a parameter of type MouseEvent, which has a stopPropagation method. However, I encountered an error when trying to fire this method and even mocking the MouseEvent did not resolve the issue.
TypeError: evt.stopPropagation is not a function
Testing Setup
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import {BrowserDynamicTestingModule} from '@angular/platform-browser-dynamic/testing';
import { ModalDialogConfig } from './config/modal-dialog.config';
import { SharedModule } from '../../shared.module';
import { ExampleComponent } from 'src/app/components/example/example.component';
import { ModalDialogModule } from '../../modal-dialog.module';
import { ModalDialogComponent } from './modal-dialog.component';
import { ModalDialogRef } from './config/modal-dialog-ref';
import { Observable } from 'rxjs';
import { NgxsModule } from '@ngxs/store';
import { Mock } from 'ts-mocks';
describe('ModalDialogComponent', () => {
let component: ModalDialogComponent;
let childComponent: ExampleComponent;
let fixture: ComponentFixture<ModalDialogComponent>;
let childFixture: ComponentFixture<ExampleComponent>;
let mockMouseEvent;
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [SharedModule, ModalDialogModule, NgxsModule.forRoot([])],
providers: [ModalDialogConfig, ModalDialogRef ]
})
.overrideModule(BrowserDynamicTestingModule, { set: { entryComponents: [ModalDialogComponent, ExampleComponent] } })
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(ModalDialogComponent);
childFixture = TestBed.createComponent(ExampleComponent);
mockMouseEvent = new Mock<MouseEvent>({ stopPropagation: () => Promise.resolve(true) });
component = fixture.componentInstance;
childComponent = childFixture.componentInstance;
component.childComponentType = ExampleComponent;
component.componentRef = childFixture.componentRef;
spyOn(component.componentRef.instance, 'closeModal').and.returnValue(Observable.of(true));
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
it('should call destroy ', () => {
spyOn(component.componentRef, 'destroy').and.callThrough();
component.ngOnDestroy();
expect(component.componentRef.destroy).toHaveBeenCalled();
});
it('should trigger onDialogClicked on click', () => {
fixture.detectChanges();
spyOn(component, 'onDialogClicked').and.callThrough();
const overlay = fixture.debugElement.query(By.css('.dialog'));
overlay.triggerEventHandler('click', {});
fixture.detectChanges();
expect(component.onDialogClicked(mockMouseEvent)).toHaveBeenCalled();
});
});
Component Implementation
onDialogClicked(evt: MouseEvent) {
evt.stopPropagation();
}