簡體   English   中英

如何為Angular中的輸入更改編寫測試用例

[英]How to write a test case for input changes in Angular

嗨,我正在使用Angular和TypeScript開發應用程序。

以下是模板代碼:

<input type="text" placeholder="Search Results" (input)="searchInput($event)">

和我關於searchInput方法的打字稿代碼是:

searchInput(event: Event & { target: HTMLInputElement}) {
   const { value } = event.target;
   this.value = value;
    // calling other method to reset values
  }

我想知道如何在我的spec.ts文件中編寫輸入測試用例。

describe('Component', () => {
  let component: Component;
  let fixture: ComponentFixture<Component>;
  const event = Event; // Is this fine ?
  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [
          AppModule
      ],
      providers: [
      ]
    })
    .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(Component);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('searchInput() ', () => {
    // how to approach 
  });
});

請提供一種方法來編寫測試用例。

這是編寫簡單測試用例的一種方法。

它能做什么:

  1. 創建組件
  2. 檢查,對於默認值value是falsy
  3. 通過CSS查找HTML輸入元素(您可能需要在此處更具體,具體取決於您的模板)
  4. 設置輸入元素的value並調度input event
  5. 確保已正確更新值的value

代碼 (記得要導入By ):

...    

import { By } from '@angular/platform-browser';

...

it('searchInput should update value when input changes', async(() => {
    const fixture = TestBed.createComponent(AppComponent);

    expect(fixture.debugElement.nativeElement.value).toBeFalsy()

    const el: HTMLInputElement = fixture.debugElement.query(By.css('input')).nativeElement;
    const testValue = 'some_value';

    el.value = testValue;
    el.dispatchEvent(new Event('input'));

    expect(fixture.componentInstance.value).toEqual(testValue);
}));

暫無
暫無

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

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