简体   繁体   English

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

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

Hi I am developing an application using Angular and TypeScript. 嗨,我正在使用Angular和TypeScript开发应用程序。

Following is the template code: 以下是模板代码:

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

and my typescript code regarding searchInput method is : 和我关于searchInput方法的打字稿代码是:

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

I was wondering the how to write input test cases in my spec.ts file. 我想知道如何在我的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 
  });
});

Please provide a way how I will approach for writing test cases. 请提供一种方法来编写测试用例。

Here is one way of writing a simple test case. 这是编写简单测试用例的一种方法。

What it does: 它能做什么:

  1. Creates the component 创建组件
  2. Checks that the default value for value is falsy 检查,对于默认值value是falsy
  3. Finds the HTML input element by CSS (you might need to be more specific here, depending on your template) 通过CSS查找HTML输入元素(您可能需要在此处更具体,具体取决于您的模板)
  4. Set's the value of the input element and dispatches an input event 设置输入元素的value并调度input event
  5. Makes sure that the value of value has been updated correctly 确保已正确更新值的value

Code (remember to import By ): 代码 (记得要导入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