我有一个具有所需输入的Angular 组件,如果没有提供,我会抛出错误.

export class FormValidationMessageComponent implements OnInit {
  @Input() form!: NgForm;
  @Input() field!: NgModel;

  ngOnInit(): void {
    if (typeof this.form === 'undefined') throw new Error(`The 'form' property is not set!`);
    if (typeof this.field === 'undefined') throw new Error(`The 'field' property is not set!`);
  }
}

我如何测试此行为?当没有提供任何东西时,它确实会在我的测试中抛出一个错误,但是我如何在我的expect中捕获这个错误呢?

let component: FormValidationMessageComponent;
let fixture: ComponentFixture<FormValidationMessageComponent>;

beforeEach(() => {
  TestBed.configureTestingModule({
    imports: [FormValidationMessageComponent],
  });
  fixture = TestBed.createComponent(FormValidationMessageComponent);
  component = fixture.componentInstance;
});

it('should throw an error when the `form` input is not provided', () => {
  const onInitSpy = spyOn(component, 'ngOnInit');
  component.field = {} as NgModel;

  fixture.detectChanges(); //Triggers ngOnInit()

  expect(onInitSpy).toThrow();
});

上述测试仍会抛出错误,并且测试失败

Error: The 'form' property is not set!

我也试了expect(component).toThrow();次,结果都是一样的

推荐答案

要测试组件初始化期间是否抛出错误,需要将fixture.detectChanges()包装在try-Catch块中,如下所示:

it('should throw an error when the `form` input is not provided', () => {
  const onInitSpy = spyOn(component, 'ngOnInit');
  component.field = {} as NgModel;

  try {
    fixture.detectChanges(); //Triggers ngOnInit()
  } catch (e) {
    expect(e.message).toBe(`The 'form' property is not set!`);
  }
});

Angular相关问答推荐

使用路由进行测试.为每次测试导航堆栈

文件阅读器未正确给出某些CSV文件的结果

为什么这个拦截器只在发送事件上触发,而不是在实际响应上触发?

带输入的单位测试Angular 分量.需要

AG网格Angular 快捷菜单调用函数

Angular Signals 如何影响 RXJS Observables 以及在这种情况下变化检测会发生什么

NgRx Effects 抛出类型错误,我不知道发生了什么

IonicStorageModule似乎不是 NgModule 类

MatTooltip 显示在 html 原生对话框下方

在 Angular 2 中订阅路由参数和查询参数

如何在angular 5 中获取基本网址?

URL 清理导致嵌入式 YouTube 视频的刷新

Angularmaterial步进器:禁用标题导航

angular 2 http withCredentials

样式 html,来自 Web 组件的正文

Angular 4 Bootstrap 下拉菜单需要 Popper.js

angular 5 material - 表单字段停留在 180px

如何在 angular2 中的 div 的 contenteditable 上使用 [(ngModel)]?

如何在 Angular 2 中跟踪路由?

需要选中一个复选框