Angular使用ng-mocks测试报错NG0304:未知组件ng-mocks-ButtonComponent
Angular ng-mocks测试报错NG0304解决方案
问题详情
执行ButtonComponent的测试用例时,抛出如下错误:
console.error
NG0304: 'ng-mocks-ButtonComponent' 不是已知元素(用于'i'组件的模板中):
- 如果'ng-mocks-ButtonComponent'是Angular组件,请确认它已在该组件所属的@NgModule中声明。
- 如果'ng-mocks-ButtonComponent'是Web组件,请将'CUSTOM_ELEMENTS_SCHEMA'添加到该组件的'@NgModule.schemas'中以屏蔽此消息。
测试代码:
describe('ButtonComponent', () => { beforeEach(() => { return MockBuilder(ButtonComponent, ButtonModule); }); it('should create', () => { const fixture = MockRender(ButtonComponent); expect(fixture.point.componentInstance).toBeDefined(); }); it('should have icon as input decorator for the button component', () => { const fixture = MockRender(ButtonComponent); expect(fixture.point.componentInstance.icon).toBeDefined(); }); });
错误原因
该错误是因为ng-mocks生成的ng-mocks-ButtonComponent未被测试模块识别,通常出现在以下场景:
- ButtonComponent的模板中递归引用了自身(比如使用
<app-button>标签) - MockBuilder的配置未正确处理组件的声明逻辑,导致原组件被mock替换后未在测试模块中注册
解决方法
方法1:显式保留原组件
修改MockBuilder配置,明确保留ButtonComponent,仅mock模块内的其他依赖:
beforeEach(() => { return MockBuilder(ButtonComponent, ButtonModule) .keep(ButtonComponent); // 阻止ng-mocks将原组件替换为mock版本 });
方法2:使用模板语法渲染组件
通过MockRender的模板字符串方式渲染组件,避免直接传入组件类触发模板递归问题:
it('should create', () => { const fixture = MockRender(`<app-button></app-button>`); expect(fixture.componentInstance).toBeDefined(); }); it('should have icon as input decorator for the button component', () => { const fixture = MockRender(`<app-button [icon]="'demo-icon'"></app-button>`); expect(fixture.componentInstance.icon).toBe('demo-icon'); });
方法3:临时添加schema屏蔽错误(不推荐)
若需快速屏蔽错误(不解决根源),可在测试模块中添加CUSTOM_ELEMENTS_SCHEMA:
beforeEach(() => { return MockBuilder(ButtonComponent, ButtonModule) .configureTestingModule({ schemas: [CUSTOM_ELEMENTS_SCHEMA] }); });
注意:此方法仅隐藏错误,无法排查模板中的实际问题,不建议作为长期解决方案。
内容的提问来源于stack exchange,提问作者user2148340
相关产品推荐
相关产品推荐

