为何Karma测试运行时无Angular应用显示?
Angular测试时
ng test页面空白问题排查方案 检查Karma配置文件(
karma.conf.js)的浏览器启动项
默认如果配置的是ChromeHeadless,会以无界面模式运行测试,自然看不到应用界面。把browsers项改成Chrome:module.exports = function(config) { config.set({ // 其他配置项... browsers: ['Chrome'], // 其他配置项... }); };确认测试是否加载了应用根组件
Angular测试默认只针对单个组件/模块执行测试逻辑,不会自动启动整个应用。如果要看到应用界面,需要在测试文件中显式初始化根组件。比如在app.component.spec.ts中保留完整的组件渲染测试:import { TestBed } from '@angular/core/testing'; import { AppComponent } from './app.component'; describe('AppComponent', () => { beforeEach(async () => { await TestBed.configureTestingModule({ declarations: [AppComponent], }).compileComponents(); }); it('should render the app', () => { const fixture = TestBed.createComponent(AppComponent); fixture.detectChanges(); // 触发组件渲染 }); });查看测试运行日志与浏览器控制台
执行ng test后,留意终端输出的报错信息;也可以点击测试页面的"Debug"按钮,打开调试窗口后查看浏览器控制台的错误,很多时候页面空白是因为组件依赖缺失、模块导入错误导致的。检查测试配置文件的其他项
如果你更新过angular.json里的测试配置,确保test下的options没有禁用界面相关的设置,比如codeCoverage开启不会导致空白,但如果有额外的自定义配置,需要确认是否影响了组件渲染。
内容的提问来源于stack exchange,提问作者Alexandr Starchenkov
相关产品推荐
相关产品推荐

