单元测试Angular 2中的属性指令

时间:2017-05-26 18:31:02

标签: angular jasmine directive

我正在尝试对具有Input参数的自定义maxlength指令进行单元测试。该指令如下:

    @Component({
      template: `<input type="text" limit="8"
                        limitTo>`
    })
    class TestMaxLengthComponent {
    }

    describe('Directive: LimitToDirective', () => {

      let component: TestMaxLengthComponent;
      let fixture: ComponentFixture<TestMaxLengthComponent>;
      let inputEl: DebugElement;

      beforeEach(() => {
        TestBed.configureTestingModule({
          declarations: [TestMaxLengthComponent, LimitToDirective]
        });

        fixture = TestBed.createComponent(TestMaxLengthComponent);
        component = fixture.componentInstance;
        inputEl = fixture.debugElement.query(By.css('input'));
      });

      it('should do something', () => {
        const event = {
          target: {
            value: '12341111'
          },
          preventDefault: function () {

          }
        };

        spyOn(event, 'preventDefault');
        inputEl.triggerEventHandler('keypress', event);
        fixture.detectChanges();
        expect(event.preventDefault).toHaveBeenCalled();
      });
    });

单元测试如下:

limit

当我运行单元测试时,我得到{{1}}的未定义值。为什么这个值未定义?

1 个答案:

答案 0 :(得分:3)

将fixture.detectChanges()移到顶部。

  it('should do something', () => {
    fixture.detectChanges();

    const event = {
      target: {
        value: '12341111'
      },
      preventDefault: function () {
      }
    };

    spyOn(event, 'preventDefault');
    inputEl.triggerEventHandler('keypress', event);

    expect(event.preventDefault).toHaveBeenCalled();
  });

另外我认为您需要更改指令以将限制字符串转换为数字:

   if (event.target.value.length === +this.limit) {