Jest.js 如何解决错误“无法系结至'ngIf',因为它不是'span'的已知属性”

lrpiutwd  于 2022-12-08  发布在  Jest
关注(0)|答案(1)|浏览(141)

我在Jest testing framework的帮助下在Angular 12应用程序中开发单元测试。现在在测试运行后的子组件中出现控制台错误 “无法绑定到'ngIf',因为它不是'span a的已知属性”
顺便说一下,在*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
1.将CommonModule导入到组件的.spec文件中
1.在TestBed提供者中包含元件
1.重新运行应用程序(多次)。
1.已将NO_ERRORS_SCHEMA添加到schema数组中
但是,错误消息仍然出现。

nzk0hqpo

nzk0hqpo1#

我通过在父规范组件的声明数组中添加子组件来修复它,它应该如下所示:

describe('ParentNameComponent', () => {
  let component: ParentNameComponent;
  let fixture: ComponentFixture<ParentNameComponent>;

  beforeEach(async () => {
     await TestBed.configureTestingModule({
     imports: [CommonModule],
     // add your child component here
     declarations: [ParentNameComponent, MonthNameComponent],
     providers: [],
   }).compileComponents();

    fixture = TestBed.createComponent(ParentNameComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });
});

相关问题