测试打字稿装饰器

时间:2019-03-07 09:56:29

标签: javascript typescript unit-testing jasmine decorator

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

执行测试时出现此错误:

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

});

1 个答案:

答案 0 :(得分:0)

经过几天的失败和审判,我认为它是我们的。看来我在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();
  });

});