【问题标题】:Angular: How test keyboard event in jasmine unit testingAngular:如何在茉莉花单元测试中测试键盘事件
【发布时间】:2020-03-09 14:57:17
【问题描述】:

我创建了自定义指令来填充自动破折号。这是stackblitz 中的完整自定义指令代码。我可以知道如何在 jasmine 中测试 ma​​sk.ts 中的以下几行(单元测试)吗?

ma​​sk.ts

@HostListener('input', ['$event'])
  onKeyDown(event: KeyboardEvent) {
    const input = event.target as HTMLInputElement;
    let trimmed = input.value.replace(/\s+/g, '');

ma​​sk.spec.ts

@Component({
  template: `
    <input type="text" dobMask />
  `,
})
class TestdobMaskComponent {}

describe('dobMask', () => {
  let component: TestdobMaskComponent;
  let fixture: ComponentFixture<TestdobMaskComponent>;
  let inputEl: DebugElement;

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

    fixture = TestBed.createComponent(TestdobMaskComponent);
    component = fixture.componentInstance;
    inputEl = fixture.debugElement.query(By.css('input'));
  });
  it('should auto populate dash when reach 6 characters', () => {
    const input = inputEl.nativeElement as HTMLInputElement;
  });
});

【问题讨论】:

标签: angular unit-testing karma-jasmine directive keyboard-events


【解决方案1】:

试试:

it('should auto populate dash when reach 6 characters', () => {
    const input = inputEl.nativeElement as HTMLInputElement;
    input.dispatchEvent(new KeyboardEvent('keydown', { key: ' ' }));
    // put a console.log in onKeyDown to make sure it is triggered.
    fixture.detectChanges();
    // grab a new reference
    const newInputEl = fixture.debugElement.query(By.css('input')) as HTMLInputElement;
    // trimmed is a local variable to the function so I don't know how you're going to test it
   // expect the space got trimmed
    expect(newInputEl.nativeElement.value).toEqual(""); 
  });

【讨论】:

  • 现在输入返回true。我怎样才能达到let trimmed = input.value.replace(/\s+/g, '');
  • 检查我的编辑,trimmed 是一个局部变量,所以很难测试。
猜你喜欢
  • 2022-01-23
  • 1970-01-01
  • 2017-09-27
  • 1970-01-01
  • 2020-11-25
  • 2015-04-11
  • 2023-03-23
  • 1970-01-01
相关资源
最近更新 更多