出现此问题的原因是在单元测试中同时存在多个组件与特定的标签名匹配的节点,导致测试框架无法确定要测试的是哪个组件,从而引发测试失败。解决的方法是在测试用例中设置唯一的customElementTag,以确保每个测试只测试一个组件。
以下是针对示例代码的
@Component({ selector: 'app-test', template: '
' }) class TestComponent { }describe('TestComponent', () => { beforeEach(() => { TestBed.configureTestingModule({ declarations: [ TestComponent, OtherComponent // 假设其他组件也使用了
it('should pass', () => { TestBed.overrideComponent(TestComponent, { set: { customElementTag: 'app-test' } // 设置唯一的 customElementTag }); const fixture = TestBed.createComponent(TestComponent); fixture.detectChanges(); expect(true).toBeTruthy(); }); });