I have created a simple decorator that can trigger either stopPropagation() or preventDefault() based on certain conditions. I have thoroughly tested this decorator in my application and am confident that it works correctly. However, I encountered an issue when trying to test whether the specified methods are actually being triggered.
During the testing process, I encountered the following error:
Error: Expected spy stopPropagation to have been called.
core.decorators.ts
export function eventModifier( stopPropagation = false, preventDefault?: boolean ) {
return function (target: any, propertyKey: string, descriptor: PropertyDescriptor) {
const originalMethod = descriptor.value;
descriptor.value = function() {
const context = this;
const mouseEvent: MouseEvent = Array.from( arguments ).find( event => event instanceof MouseEvent );
if ( stopPropagation ) {
mouseEvent.stopPropagation();
}
if ( preventDefault ) {
mouseEvent.preventDefault();
}
originalMethod.apply( context, arguments );
};
return descriptor;
};
}
core.decorators.spec.ts
import { eventModifier } from './core.decorators';
describe('eventModifier decorator', () => {
class TestClass {
@eventModifier( true )
public click( event: MouseEvent ): void {
}
}
it('should define the decorator', function() {
expect( eventModifier ).toBeDefined();
});
it('stopPropagation() should be called', function() {
const testClass = new TestClass();
const ev = new MouseEvent('click')
spyOn( testClass, 'click' );
spyOn( ev, 'stopPropagation' );
testClass.click( <MouseEvent> ev );
expect( testClass.click ).toHaveBeenCalledWith( ev );
expect( ev.stopPropagation ).toHaveBeenCalled();
});
});