【问题标题】:Unit test angular form to ensure form cannot be submitted unless required fields are provided单元测试角度表单,以确保除非提供必填字段,否则无法提交表单
【发布时间】:2017-06-08 11:09:03
【问题描述】:

使用下面的测试,我看到我的代码覆盖率是这样的:

public onSubmit() { this.submitted = true; }

在执行时,即使我没有在title 文本字段中输入数据.. 为什么会这样?

如何测试这种逻辑?

dummy.component.ts

import { Component } from '@angular/core';

@Component({
  selector: 'my-selector',
  templateUrl: './dummy.component.html'
})
export class DummyComponent {

  public submitted = false;
  public onSubmit() { this.submitted = true; }
}

dummy.component.html

<div class="container">
  <div [hidden]="submitted">
    <h1>New Page Form</h1>
    <form (ngSubmit)="onSubmit()" #pageForm="ngForm">
      <div>
        <label for="title">Title</label>
        <input type="text" id="title" required [(ngModel)]="model.title" name="title" #title="ngModel">
        <div [hidden]="title.valid || title.pristine">
          Title is required
        </div>
      </div>

      <button id="submitNewPage" type="submit" [disabled]="!pageForm.form.valid">Finish</button>
    </form>
  </div>

  <div [hidden]="!submitted">
    <h2>New page details:</h2>
    <div>
      <div>Title: {{ model.title }}</div>
    </div>
    <br>
    <button (click)="submitted=false">Edit</button>
  </div>
</div>

dummy.component.spec.ts

it('should create an instance of PageFormComponent', () => {
  fixture.debugElement.nativeElement.querySelector('#submitNewPage').click();
});

【问题讨论】:

    标签: angular unit-testing typescript


    【解决方案1】:

    您确定使用 click() 以正确的方式触发事件吗?因为据我所知应该是一些东西

      describe('your block', () => {
         let submitB;
        beforeEach(() => {
           submitB = fixture.debugElement.nativeElement.query(By.css('#submitNewPage'));
           submitB.dispatchEvent(new Event('click'))
         });
    
        it('your expectation' () => {})
       })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-10-26
      • 2020-04-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-28
      • 2011-10-31
      • 1970-01-01
      相关资源
      最近更新 更多