我正在借助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();
});
});
笔记:
我已阅读有关此错误的多项建议并做了以下事情:
- 检查是否存在
CommonModule
包含此组件的延迟加载模块 - 导入
CommonModule
到.spec
组件文件中 - 将组件包含在
TestBed
提供程序中 - 重新运行应用程序(多次)。
- 添加
NO_ERRORS_SCHEMA
到schema
数组中
但是,错误消息仍然出现。