运行时加载环境数据致Angular测试注入字段异常求助
Angular动态加载配置后测试出现组件初始化错误
我们移除了环境文件,改为在启动AppModule前通过fetch加载配置数据,但测试文件中出现注入字段未定义的问题。
核心代码
main.ts
fetch('./assets/config/config.json') .then(response => response.json()) .then((config: AppConfig) => { platformBrowserDynamic([{ provide: APP_CONFIG, useValue: config }]).bootstrapModule(AppModule) .catch(err => console.error(err)); });
app.module.ts
... export class AppModule { } export const APP_CONFIG = new InjectionToken<AppConfig>('ENV_DATA');
服务注入方式
constructor(@Inject(APP_CONFIG) private config: AppConfig) {}
测试报错情况
在app.component.spec.ts中,若应用使用了依赖APP_CONFIG的ItemsService,测试会抛出以下错误:
Uncaught ReferenceError: Cannot access 'AppComponent' before initialization ReferenceError: Cannot access 'AppComponent' before initialization
测试文件代码:
describe('AppComponent', () => { beforeEach(async () => { await TestBed.configureTestingModule({ imports: [ RouterTestingModule ], declarations: [ AppComponent ], }).compileComponents(); }); it('should create the app', () => { const fixture = TestBed.createComponent(AppComponent); const app = fixture.componentInstance; expect(app).toBeTruthy(); }); });
即使在configureTestingModule的providers数组中注入{provide: APP_CONFIG, useValue: {}},错误仍存在。尝试在it用例中通过inject实例化组件并注入服务,也无法解决:
it('should check service injection', inject([ItemsService], (itemsService: ItemsService) => { let fix = TestBed.createComponent(AppComponent); let comp = fix.componentInstance; expect(comp).toBeTruthy(); }));
异常现象
若在ItemsService中注入字符串令牌,即:
constructor(@Inject('ENV_DATA') private config: AppConfig) {}
测试可正常运行(需在configureTestingModule中注入'ENV_DATA'),但项目构建会失败,因为应用中未注入'ENV_DATA'。
有人遇到过类似问题吗?求解答!
内容的提问来源于stack exchange,提问作者AlleXyS
相关产品推荐
相关产品推荐

