Angular 5 Karma-Jasmine测试报错:Cannot call Promise.then from sync test
解决Angular 5中Karma-Jasmine测试的
Cannot call Promise.then from within a sync test错误 这个错误的核心原因是你在**fakeAsync包裹的同步测试上下文里调用了Promise的.then()方法**,同时测试代码还有几个小问题需要调整,下面一步步帮你修复:
1. 修复beforeEach中的异步处理问题
你在fakeAsync里使用了.compileComponents().then(),这会触发同步测试上下文里的Promise调用,直接导致报错。其实在Angular CLI生成的项目中,组件已经被预编译,通常不需要手动调用compileComponents();如果确实需要处理编译的异步逻辑,应该用async包裹beforeEach,而非fakeAsync。
2. 调整commentService的赋值位置
你现在把commentService = TestBed.get(CommentService)放在了beforeEach和it块外面,这会导致在TestBed还没完成配置就尝试获取服务,应该把它移到beforeEach内部,确保组件编译完成后再获取服务实例。
3. 简化afterEach的处理
afterEach只是做变量清理,不需要用fakeAsync包裹,直接同步处理即可。
修复后的测试代码
fdescribe('CommentComponent', () => { let component: CommentComponent; let fixture: ComponentFixture<CommentComponent>; let commentService: CommentService; const stationId = 900; let station: Station; let comment: Comment; beforeEach(async(() => { station = new Station(); station.id = stationId; comment = new Comment('', null, null, ''); TestBed.configureTestingModule({ declarations: [ CommentComponent ], providers: [ CommentService, StationService ], imports: [ HttpClientTestingModule, FormsModule, RouterTestingModule, MatSnackBarModule, NgxPaginationModule, BrowserAnimationsModule ], schemas: [NO_ERRORS_SCHEMA, CUSTOM_ELEMENTS_SCHEMA] }) .compileComponents(); })); // 拆分出单独的beforeEach,确保编译完成后初始化组件和服务 beforeEach(() => { fixture = TestBed.createComponent(CommentComponent); component = fixture.componentInstance; commentService = TestBed.get(CommentService); fixture.detectChanges(); }); afterEach(() => { component = null; fixture.destroy(); commentService = null; comment = null; }); it('should create', () => { expect(component).toBeTruthy(); }); });
额外优化建议
你的组件在ngOnInit里调用了getComment()发起HTTP请求,建议在测试中mockCommentService的方法,避免依赖真实后端服务:
// 在beforeEach的providers里替换为mock服务 providers: [ { provide: CommentService, useValue: { getComments: jasmine.createSpy('getComments').and.returnValue(of([])), saveComment: jasmine.createSpy('saveComment').and.returnValue(of(new Comment())) }}, StationService ],
这样能让测试更稳定,也避免了不必要的网络请求。
内容的提问来源于stack exchange,提问作者John Doiron
相关产品推荐
相关产品推荐

