【问题标题】:Trouble unit testing angular reactive form control reset from button click故障单元测试从按钮单击重置角度反应形式控制
【发布时间】:2022-02-06 23:44:07
【问题描述】:

我在为我的 Angular 应用程序编写 jasmine 单元测试用例时遇到了问题。 有一个响应式表单并尝试通过单击按钮重置特定表单控件。 尽管场景应该足够简单,可以测试,但我似乎在这里遗漏了一些东西。

以下是应用程序中的代码 sn-p。

app.component.html:

<form [formGroup]="userForm" novalidate (ngSubmit)="onSubmit()">
  <div>
    <input
      type="text"
      id="fNameFld"
      name="fName"
      formControlName="fName"
      placeholder="First Name"
    />
    <button (click)="clearField('fName')" id="clrFName">
      Clear First Name
    </button>
  </div>

  <div>
    <input
      type="text"
      id="lNameFld"
      name="lName"
      formControlName="lName"
      placeholder="Last Name"
    />
    <button (click)="clearField('lName')" id="clrLName">Clear Last Name</button>
  </div>

  <div>
    <button type="submit">Submit</button>
  </div>
</form>

app.component.ts

import { FormBuilder, FormGroup } from '@angular/forms';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent implements OnInit {
  name = 'Angular ' + VERSION.major;
  userForm: FormGroup;

  constructor(private readonly fb: FormBuilder) {}

  ngOnInit() {
    this.userForm = this.fb.group({
      fName: this.fb.control(null),
      lName: this.fb.control(null),
    });
  }

  onSubmit() {
    console.log('Submitted Data', this.userForm.value);
  }

  clearField(controlName: string) {
    this.userForm.get(controlName).reset();
  }
}

单元测试代码

it('should clear fName control when the "Clear First Name" button is clicked', () => { 
    const spy = spyOn(component, 'clearField');
    const clearBtn = fixture.debugElement.query(By.css("button#clrFName"));
    const form = component.userForm;
    
    form.patchValue({
      'fName': 'John,
      'lName': 'Doe'
    });
    
    clearBtn.nativeElement.click();
    fixture.detectChanges();
    expect(spy).toHaveBeenCalledTimes(1);  // passes
    expect(spy).toHaveBeenCalledWith('fName');  // passes
    expect(form.get('fName').value).toBeNull();  // fails: Expected 'John' to be null.
  });

角度:10.0.14

Angular CLI:10.0.8

StackBlitz:https://angular-ivy-fc6rik.stackblitz.io

【问题讨论】:

    标签: javascript html angular jasmine


    【解决方案1】:

    好像你在嘲笑clearField。添加它以在您模拟它时实际执行其内容:

    const spy = spyOn(component, 'clearField').and.callThrough();
    

    所以每次调用clearField,它都会触发spy(这样你就知道它是否被调用了),并且会执行它的内容。

    【讨论】:

    • 你是摇滚明星!!你的解决方案对我有用,单元测试用例现在通过了。
    猜你喜欢
    • 1970-01-01
    • 2018-06-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多