Angular 单元测试 - 如何测试反应式表单重置方法?

问题描述 投票:0回答:2

我正在尝试测试这个方法:

doResetForm(){
   this.form.reset();
}

所以我尝试了:

it('should reset the form', () => {
   const spyformReset = jest.spyOn(component.form, 'reset');
   
   fixture.detectChanges();
   component.doResetForm();
   expect(spyformReset).toHaveBeenCalled();
}

但我收到错误:

无法监视原始值,未定义的给出

angular unit-testing jestjs jasmine
2个回答
0
投票

您可以使用 spyOn 来模拟该方法。

const spyformReset = spyOn(component.form, 'reset').and.callThrough();
component.doResetForm();
expect(spyformReset).toHaveBeenCalled();

0
投票

对我来说这有效:

   it('should reset the form', () => {
    form.reset();

    // Verify if the form has been reset
    expect(form.value).toEqual({
      name: null,
      email: null
    });

    // Verify if the form is invalid before reset
    expect(form.valid).toBeFalse();
  });

是一个简单的解决方案。我希望它对你有用。

© www.soinside.com 2019 - 2024. All rights reserved.