如果表单无效,如何触发按钮的“禁用”属性验证?

时间:2019-01-05 10:43:07

标签: javascript html angular

我正在测试我的有角度的应用程序,并且有组件,如果表单无效,我想检查按钮是否被禁用。但是未添加disabled属性。我在做什么错了?

我试图创建一个模拟表单,但也未得到验证。 还尝试将其本机设置为html并分派输入事件,这也不起作用:

it('submit button should be disabled if form is invalid', async() => {
    const inputDe = fixture.debugElement.nativeElement.querySelector('input[name="amount"]');
    const inputEl = inputDe.nativeElement;
    inputDe.value = 'test';
    inputDe.dispatchEvent(new Event('input'));
    fixture.detectChanges();
    const compiled = fixture.debugElement.nativeElement;
    expect(compiled.querySelector('.btn-success').getAttribute('disabled')).toBeTruthy();
  });

这是我的代码:

shopping-edit.component.ts

@Component({
selector: "app-shopping-edit",
templateUrl: "./shopping-edit.component.html",
styleUrls: ["./shopping-edit.component.css"]
})
export class ShoppingEditComponent implements OnInit, OnDestroy {

@ViewChild('form') form: NgForm;
} 

shopping-edit.component.html

<div class="row">
  <div class="col-xs-12">
    <form (ngSubmit)="onSubmit()" #form="ngForm">
      <div class="row">
        <div class="col-sm-5 form-group">
          <label for="name">Name</label>
          <input ngModel name="name" type="text" id="name" class="form-control" required>
        </div>
        <div class="col-sm-2 form-group">
          <label for="amount">Amount</label>
          <input ngModel name="amount" type="number" id="amount" class="form-control" required pattern="^[1-9]+[0-9]*$" >
        </div>
      </div>
      <div class="row">
        <div class="col-xs-12">
      <button class="btn btn-success" type="submit" [disabled]="!form.valid">{{ editMode ? 'Update' : 'Add' }}</button>
    </div>
  </div>
</form>

shopping-edit.component.spec.ts

describe('ShoppingEdit component', () => {
  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [
        FormsModule
      ],
      declarations: [ShoppingEditComponent]
    });
    fixture = TestBed.createComponent(ShoppingEditComponent);
  });

  it('submit button should be disabled if form is invalid', async() => {
    // const testForm = <NgForm>{
    //   valid: false
    // };
    setTimeout(() => {
      fixture.debugElement.componentInstance.form.setValue({name: '', amount: 'a555'});
    }, 1000);
    fixture.detectChanges();
    const compiled = fixture.debugElement.nativeElement;
    expect(compiled.querySelector('.btn-success').getAttribute('disabled')).toBeTruthy();
  });
});

有什么想法吗?

0 个答案:

没有答案