簡體   English   中英

Karma 測試粘貼事件

[英]Karma test paste event

我有一個簡單的組件來處理粘貼事件到表單輸入中。

表格:

this.searchForm = this.formBuilder.group({
  query: [ null, [Validators.required] ]
});

onPaste(event) {
    event.preventDefault();
    const formattedQuery = event.clipboardData.getData('text/plain')
      .split(/,?[\r\n\t]+\s?/)
      .join(', ')
      .replace(/,\s?$/g, '');

    this.searchForm.get('query').setValue(formattedQuery);
  }

現在我正在嘗試測試它,它看起來像這樣:

it('should reformat pasted data', () => {
    const queryField = fixture.debugElement.query(By.css('input[type="search"]'));
    queryField.nativeElement.dispatchEvent(new ClipboardEvent('paste', {
      dataType: 'text/plain', 
      data: '123\r123'
    }));
    fixture.detectChanges();
    expect(queryField.nativeElement.value).toBe('123, 123');
    // also tried expect(component.searchForm.get('query').value).toBe('123, 123');
  });

但結果我有

Expected '' to be '123, 123'

如果我執行console.log(queryField.nativeElement)它會顯示輸入,但為什么它不處理new ClipboardEvent('paste')事件?

<input class="ng-untouched ng-pristine ng-invalid" formcontrolname="query" type="search" ng-reflect-name="query">

您可以在這里找到完整的組件https://stackblitz.com/edit/angular-cp9yhx?file=app%2Fhello.component.ts

我的單元測試有什么問題?

試試這個:

it('should reformat pasted data', () => {
  component.onPaste(new ClipboardEvent('paste', {
    dataType: 'text/plain', 
    data: '123\r123'
  }));
  expect(queryField.nativeElement.value).toBe('123, 123');
});

甚至

it('should reformat pasted data', () => {
  component.onPaste(new ClipboardEvent('paste', {
    dataType: 'text/plain', 
    data: '123\r123'
  }));
  expect(component.searchForm.get('query').value).toBe('123, 123');
});

這對我有用:

it('should trim pasted data', () => {
  const initialValue = 'test ';
  fixture.detectChanges();

  // Setting initial value
  const el = inputElement.nativeElement;
  el.value = initialValue;

  // Setting up event data
  const pasteData = new DataTransfer();
  pasteData.setData('text', initialValue);

  // Creating event
  const pasteEvent = new ClipboardEvent('paste', {
    clipboardData: 'new value'  <- CHANGED
  } as any);


  // Dispatching event    
  el.dispatchEvent(pasteEvent);

  expect(el.value).toEqual('new value'); <- CHANGED
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM