【问题标题】:How to write a test case for input changes in Angular如何为 Angular 中的输入更改编写测试用例
【发布时间】:2017-11-22 12:28:39
【问题描述】:

您好,我正在使用 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 
  });
});

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

【问题讨论】:

  • 您可以查看@this repo 并检查规范文件,它非常基本但会帮助您我猜github.com/rahulrsingh09/AngularConcepts
  • 感谢您的链接,但它并没有解决我的问题。
  • @Vaibhav 到目前为止你有什么尝试?
  • 我还在寻找方法,我是新手。如果您有任何想法,请提出建议。
  • 如果我是你,我唯一会做的就是expect(component.value).toEqual(/*your value*/);(当然,之前打电话给component.searchInput()

标签: angular typescript testing jasmine karma-jasmine


【解决方案1】:

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

它的作用:

  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);
}));

【讨论】:

  • 这就是我正在寻找的感谢代码。如果可能的话,请您提供一些链接以了解 jasmin 测试语言。这样我就可以清楚地了解如何使用。
  • @Vaibhav 乐于助人!您是否尝试过 anglar.io 上的官方指南?我认为这是一个很好的资源:@​​987654321@
  • 感谢您的链接和帮助。
  • el.dispatchEvent(new Event('input'));救了我! :) 谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-06-30
  • 1970-01-01
  • 2021-03-03
  • 1970-01-01
  • 2019-05-01
  • 1970-01-01
相关资源
最近更新 更多