Angular私有库测试:.spec.ts中创建测试组件/模块报错解决
Angular测试组件类装饰器错误的解决方案
方法1:在测试文件内直接通过TestBed声明测试组件
无需将测试组件抽离到单独模块,直接在.spec.ts中定义测试组件后,在TestBed的配置里声明它即可。这种方式让测试组件属于当前测试模块的一部分,不需要关联主模块,就能解决装饰器上下文错误。
示例代码:
// 定义内部测试组件 @Component({ template: `<app-input-show [inputData]="testData"></app-input-show>` }) class TestInputShowComponent { testData = '测试数据'; } describe('InputShowComponent', () => { let component: InputShowComponent; let fixture: ComponentFixture<InputShowComponent>; beforeEach(async () => { await TestBed.configureTestingModule({ declarations: [InputShowComponent, TestInputShowComponent] // 同时声明目标组件和测试组件 }).compileComponents(); }); // 编写测试用例... });
方法2:检查并修正tsconfig.spec.json配置
测试环境的TypeScript配置异常也会触发该错误,确保tsconfig.spec.json符合以下要求:
compilerOptions.target设置为与主项目一致的版本(如ES2020)- 开启
experimentalDecorators和emitDecoratorMetadata types数组包含jasmine和node
示例配置片段:
{ "extends": "./tsconfig.json", "compilerOptions": { "outDir": "./out-tsc/spec", "types": ["jasmine", "node"], "experimentalDecorators": true, "emitDecoratorMetadata": true }, "include": ["src/**/*.spec.ts", "src/**/*.d.ts"] }
方法3:同步Angular依赖版本
@angular/core与TypeScript版本不兼容是常见诱因,运行以下命令更新到匹配的版本(可参考Angular官方文档的版本对应表):
npm install @angular/core@latest typescript@latest --save-dev
内容的提问来源于stack exchange,提问作者Dudu
相关产品推荐
相关产品推荐

