I have a simple decorator to trigger either stopPropagation() or preventDefault() when certain conditions are met. I've tested this in my app and I'm sure the decorator is working properly. However I couldn't test the decorator, whether the aforementioned methods are triggered.
When executing the test I get this 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('decorator is defined', 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();
});
});
After couple of days of fail and trial I figured it our. It appears that I forgot something while setting spy on testClass.click method.
Here is the working unit test:
import { eventModifier } from './core.decorators';
describe('eventModifier decorator', () => {
class TestClass {
@eventModifier( true )
public click( event: MouseEvent ): void {
}
}
it('decorator is defined', function() {
expect( eventModifier ).toBeDefined();
});
it('stopPropagation() should be called', function() {
const testClass = new TestClass();
const ev = new MouseEvent('click')
spyOn( testClass, 'click' ).and.callThrough();
spyOn( ev, 'stopPropagation' );
testClass.click( <MouseEvent> ev );
expect( testClass.click ).toHaveBeenCalledWith( ev );
expect( ev.stopPropagation ).toHaveBeenCalled();
});
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.