除非提供必要的字段,否则不能提交单元测试角形以确保形式

时间:2017-06-08 11:09:03

标签: angular unit-testing typescript

使用下面的测试,我发现我的代码覆盖率看到了这一点:

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

1 个答案:

答案 0 :(得分:0)

你是否确定即使用click()以正确的方式触发事件?因为据我所知应该是什么

!G || G == 0