我有一个简单的装饰器,可以在满足某些条件时触发stopPropagation()或preventDefault()。我已经在我的应用中对此进行了测试,并且确定装饰器可以正常工作。但是我无法测试装​​饰器,是否触发了上述方法。

执行测试时,出现此错误:

 Error: Expected spy stopPropagation to have been called.


核心装饰器

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;
  };
}


核心装饰器规格

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();
  });

});

最佳答案

经过几天的失败和审判,我认为它是我们的。看来我在testClass.click方法上设置间谍时忘记了一些东西。

这是工作单元测试:

 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();
  });

});

10-07 21:32