【问题标题】:Jest console.error NG0303: Can't bind to 'formGroup' since it isn't a known property of 'form'开玩笑的 console.error NG0303:无法绑定到“formGroup”,因为它不是“form”的已知属性
【发布时间】:2021-08-20 22:29:42
【问题描述】:

我正在使用 Jest 和 Angular 11 测试一个具有响应式表单的组件。测试似乎表现正确,但是当我运行测试时,此错误消息充斥着控制台。这些错误不会在我发球时出现,仅在测试期间出现。 (编辑了一些文件名)

console.error NG0303: Can't bind to 'formGroup' since it isn't a known property of 'form'.
      at logUnknownPropertyError (../packages/core/src/render3/instructions/shared.ts:1117:11)
      at elementPropertyInternal (../packages/core/src/render3/instructions/shared.ts:999:9)
      at ɵɵproperty (../packages/core/src/render3/instructions/property.ts:42:5)
      at UnderTestComponent_Template (ng:/UnderTestComponent.js:308:9)
      at executeTemplate (../packages/core/src/render3/instructions/shared.ts:511:5)
      at refreshView (../packages/core/src/render3/instructions/shared.ts:369:7)
      at refreshComponent (../packages/core/src/render3/instructions/shared.ts:1716:7)

我知道 Jest 在导入方面存在一些问题,例如我需要使用相对导入,否则 Jest 会崩溃。不知道有没有关系。

// Module for the component under test
@NgModule({
  declarations: [UnderTestComponent],
  imports: [
    CommonModule,
    SharedModule,
    ReactiveFormsModule,
    FormsModule,
    // ...
  ],
  exports: [UnderTestComponent],
  schemas: [CUSTOM_ELEMENTS_SCHEMA],
  providers: [TranslatePipe],
})
export class UnderTestModule{}
<!-- Component under test HTML snippet -->
<form novalidate (ngSubmit)="submitForm()" [formGroup]="formRoot">
  <div id="exampleDiv" class="formMember">
    <internal-input
      formControlName="example"
      type="text"
      maxLength="10"
      [allowedCharacterPattern]="numberRegex"
      id="exampleId"
    >
      <internal-input-label for="exampleId">Example Number</internal-input-label>
      <internal-message [error]="true" *ngIf="msgs.example">
        Example Number {{ msgs.example }}
      </internal-message>
    </internal-input>
  </div>
  // ...
</form>
// Jest test snippet for the component under test
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { UnderTestComponent} from './under-test.component';
import { ApiService } from '../../../services/api-service/api.service';
import { FormBuilder } from '@angular/forms';
import { CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';

describe('UnderTestComponent', () => {
  let component: UnderTestComponent;
  let fixture: ComponentFixture<UnderTestComponent>;
  const mockApiService = {
    toDoMethod: jest.fn(),
  };

  beforeEach(async () => {
    await TestBed.configureTestingModule({
      declarations: [UnderTestComponent],
      schemas: [CUSTOM_ELEMENTS_SCHEMA],
      providers: [
        FormBuilder,
        { provide: ApiService, useValue: mockApiService },
      ],
    }).compileComponents();
  });

  beforeEach(() => {
    fixture = TestBed.createComponent(UnderTestComponent);
    component = fixture.componentInstance;
  });

  describe('form:', () => {
    it.only('example too short', () => {
      fixture.detectChanges();
      let example = component.formRoot.get('example');
      example.setValue('123456789');
      expect(example.invalid).toBeTruthy();
    });
  });
}

错误不会出现在某些测试中,例如:

   it.only('ngOnInit should create a form with the correct structure', () => {
      expect(component.formRoot).toBeUndefined();
      component.ngOnInit();
      expect(component.formRoot.get('example')).toBeTruthy();
      expect(
        component.formRoot.get('groupExample').get('groupMemberExample')
      ).toBeTruthy();
    });

【问题讨论】:

    标签: angular jestjs angular-reactive-forms


    【解决方案1】:

    TestBed 模块也需要导入FormsModule。 因此,在您的测试设置中,像这样扩展模块:

    await TestBed.configureTestingModule({
        ...
        imports: [FormsModule, ReactiveFormsModule, ...]
    })
    

    【讨论】:

    • 当我添加这些导入时,测试都失败了No value accessor for form control with name: 'example' _throwError (../packages/forms/src/directives/shared.ts:301:9)
    • 已修复!我还导入了包含组件 HTML 中使用的自定义组件的模块,例如imports: [FormsModule, ReactiveFormsModule, InternalInputModule]
    • 在不包括整个模块的情况下还有其他想法吗?如果我们包括所有使用的模块/组件等,CUSTOM_ELEMENTS_SCHEMA 没有任何意义。但我想包括所有这些东西:think:
    猜你喜欢
    • 2019-08-26
    • 2019-09-19
    • 2017-09-01
    • 2017-02-26
    • 2018-02-24
    • 2021-04-08
    • 1970-01-01
    • 2021-05-08
    相关资源
    最近更新 更多