我正在try 对登录表单进行单元测试,但我无法按预期执行它.

试验台配置:

beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [FormsModule],
      declarations: [AuthComponent],
    });
    fixture = TestBed.createComponent(AuthComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });
it('form should be invalid', () => {
    component.authForm.controls['email'].markAsTouched();

    expect(component.authForm.invalid).toBeTruthy();
});

当执行上述测试时,我收到以下错误 TypeError: Cannot read properties of undefined (reading 'markAsTouched').

使用fakeAsyncwhenstable修改测试时,如下所示

it('form should be invalid', fakeAsync(() => {
    fixture.whenStable().then(() => {
      component.authForm.controls['email'].markAsTouched();
      expect(component.authForm.invalid).toBeTruthy();
    });
  }));

测试结果显示为SPEC HAS NO EXPECTATIONS form should be invalid.

不确定我做错了什么.

推荐答案

您更新的SPEC函数通过使用fakeAsync()将真实的异步代码(fixture.whenStable())与假的异步测试区域混合在一起.你得选一个.您收到这个新错误的原因是,在whenStable() Promise解析之前,函数执行已经结束.

一旦修复了不一致,它们应该以相同的方式工作,等待宏任务队列中的所有挂起任务(如setTimeout())得到解决.

"真正的"异步

it('form should be invalid', async (() => {
  await fixture.whenStable(); // wait until all pending macro tasks are resolves
  component.authForm.controls['email'].markAsTouched();
  expect(component.authForm.invalid).toBeTruthy();
}));

假异步区

it('form should be invalid', fakeAsync(() => {
  flush(); // invoke all remaining pending macro tasks.
  component.authForm.controls['email'].markAsTouched();
  expect(component.authForm.invalid).toBeTruthy();
}));

对我来说,我不知道哪个更好.另外,我不知道这是否能解决您原来的问题,因为您没有提供组件代码.

Angular相关问答推荐

Angular - MSAL用户缺少角色

单元测试 case 模拟store 中的行为主体

基于另一个控制值显示值的Angular 数组

Primeng 12Angular 12自定义库:错误符号字段集声明于...在编译保存后未从Primeng/fieldset中导出

带逻辑的组件decorator 中的Angular 主机侦听器属性

当嵌套在异步容器中时,S会阻止具有动态值的ionic 段工作吗?

所有返回缺少权限或权限不足的FireBase项目.

Angular将文件作为字符串读取给dxf解析器

Angular 迁移 14 到 15 / 16:angular universal 是否停止将 <!-- this page was prerendered with angular universal --> 用于预渲染页面?

在ngOninit方法中直接VS初始化属性

将 injectiontoken 用于 Angular 中的模块特定设置

将 html ngModel 值传递给服务Angular

Angular 2在单击子项时防止单击父项

Angular 2中基于Condition条件的点击事件

AOT - Angular 6 - 指令 SomeComponent,预期 0 个参数,但go 有 1 个参数

Angular - 工作区中未设置配置

得到了预期表达式的插值 ({{}})

Angular 2中不同页面的多种布局

有条件地将 RouterLink 或其他属性指令添加到 Angular 2 中的元素

No provider for Router?