如何在Angular变更检测触发前调用Jasmine创建的Spy方法?
在变更检测前调用Spy方法的解决方案
我来帮你搞定这个问题!其实操作起来很简单,你只需要先从TestBed中获取到注入的模拟服务实例,再直接调用对应的Spy方法就行,具体修改如下:
修改后的beforeEach代码
beforeEach(() => { fixture = TestBed.createComponent(StudentsListComponent); component = fixture.componentInstance; // 1. 获取注入的模拟学生服务实例 const studentService = TestBed.inject(StudentsCrudService) as jasmine.SpyObj<StudentsCrudService>; // 2. 调用你预设的Spy方法 studentService.getAllStudents(); // 3. 最后执行变更检测 fixture.detectChanges(); });
关键说明
- 获取服务实例:通过
TestBed.inject(StudentsCrudService)可以拿到你在测试模块中配置的模拟服务(也就是你定义的stubStudentService),用as jasmine.SpyObj<StudentsCrudService>做类型断言是为了让TypeScript识别出这是一个带有Spy方法的对象,避免类型报错。 - 调用Spy方法:直接调用
studentService.getAllStudents()就会触发你预设的and.returnValue(of(studentPayload))逻辑,同时这个调用会被Jasmine的Spy记录下来,后续你可以通过expect(studentService.getAllStudents).toHaveBeenCalled()这类断言来验证调用情况。 - 确保服务配置正确:要保证你在
TestBed.configureTestingModule中已经正确提供了这个模拟服务,比如:TestBed.configureTestingModule({ declarations: [StudentsListComponent], providers: [ { provide: StudentsCrudService, useValue: stubStudentService } ] });
这样就能在变更检测执行前,提前触发你的Spy方法啦!
内容的提问来源于stack exchange,提问作者NicoleZ
相关产品推荐
相关产品推荐

