0

我正在借助Jest 测试框架在 Angular 12 应用程序中开发单元测试。现在在测试运行后子组件中出现控制台错误“无法绑定到 'ngIf',因为它不是 'span' 的已知属性” 。

顺便说一句,检查*ngIf状态的数据是通过以下方式接收的@Input()

这是HTML:

<span class="month-name" *ngIf="name && year">
    {{ name.toUpperCase() }}
    <span class="year">{{ year }}</span>
</span>

这是 TypeScript 代码:

export class MonthNameComponent implements OnInit {
  @Input() name: string = '';
  @Input() year: string = '';

  constructor() {}

  ngOnInit(): void {}
}

最后,这是测试文件的样子:

    describe('MonthNameComponent', () => {
      let component: MonthNameComponent;
      let fixture: ComponentFixture<MonthNameComponent>;
    
      beforeEach(async () => {
         await TestBed.configureTestingModule({
         imports: [CommonModule],
         declarations: [MonthNameComponent],
         providers: [],
         schemas: [NO_ERRORS_SCHEMA]
       }).compileComponents();

        fixture = TestBed.createComponent(MonthNameComponent);
        component = fixture.componentInstance;
        fixture.detectChanges();
      });
    
      it('should create', () => {
        expect(component).toBeTruthy();
      });
    });

笔记:

我已阅读有关此错误的多项建议并做了以下事情:

  1. 检查是否存在CommonModule包含此组件的延迟加载模块
  2. 导入CommonModule.spec组件文件中
  3. 将组件包含在TestBed提供程序中
  4. 重新运行应用程序(多次)。
  5. 添加NO_ERRORS_SCHEMAschema数组中

但是,错误消息仍然出现。

4

0 回答 0