如何为 Angular 中的输入更改编写测试用例

Vai*_*hav 5 testing jasmine typescript karma-jasmine angular

嗨,我正在使用 Angular 和 TypeScript 开发一个应用程序。

以下是模板代码:

<input type="text" placeholder="Search Results" (input)="searchInput($event)">
Run Code Online (Sandbox Code Playgroud)

我关于 searchInput 方法的打字稿代码是:

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

我想知道如何在我的 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 
  });
});
Run Code Online (Sandbox Code Playgroud)

请提供一种我将如何编写测试用例的方法。

Fre*_*din 5

这是编写简单测试用例的一种方法。

它能做什么:

  1. 创建组件
  2. 检查默认值是否value为假
  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);
}));
Run Code Online (Sandbox Code Playgroud)