在 Angular 单元测试中,当使用了自定义元素(Custom Elements)时,可能会出现 CUSTOM_ELEMENTS_SCHEMA
错误。这是因为 Angular 单元测试默认使用了 NO_ERRORS_SCHEMA
模式,它不支持自定义元素。
要解决这个问题,你可以在你的测试文件中添加 CUSTOM_ELEMENTS_SCHEMA
模式。下面是一个示例:
import { ComponentFixture, TestBed, async } from '@angular/core/testing';
import { Component } from '@angular/core';
@Component({
selector: 'custom-element',
template: 'Custom Element',
})
class CustomElementComponent {}
describe('CustomElementComponent', () => {
let fixture: ComponentFixture;
let component: CustomElementComponent;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [CustomElementComponent],
schemas: ['CUSTOM_ELEMENTS_SCHEMA'], // 添加 CUSTOM_ELEMENTS_SCHEMA 模式
}).compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(CustomElementComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
在上面的示例中,我们在 schemas
属性中添加了 'CUSTOM_ELEMENTS_SCHEMA'
,以告诉 Angular 单元测试支持自定义元素。
这样做后,你的单元测试应该能够正常运行,而不会报 CUSTOM_ELEMENTS_SCHEMA
错误。