typescript - 如何為 Angular 中的輸入變更撰寫測試案例
嗨,我正在使用 Angular 和 TypeScript 開發一個應用程式。
以下是範本程式碼:
<input type="text" placeholder="Search Results" (input)="searchInput($event)">
而我關於 searchInput 方法的 TypeScript 代碼是:
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
這是一種編寫簡單測試案例的方法。
它的作用:
- 創建元件
- 檢查
value的預設值是否為假值 - 通過 CSS 查找 HTML 輸入元素(根據你的模板,你可能需要在這裡更具體一些)
- 設定輸入元素的
value並派發一個input 事件 - 確保
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);
}));
