如何在Jasmine测试中Mock @Inject('window')依赖?
正确模拟并测试注入的
window服务 当然可以在Jasmine测试里模拟你注入的window服务!你已经走对了第一步——在测试模块的providers数组里配置模拟对象,接下来我一步步帮你完善测试逻辑,确保能精准验证服务的调用行为。
1. 先把模拟对象里的方法改成Jasmine Spy
你当前的mockWindowService里,pushState是个空函数,没法验证它是否被调用。我们直接把它改成Jasmine的spy,这样就能追踪调用情况了:
// 定义带spy的模拟window服务 const mockWindowService = { history: { pushState: jasmine.createSpy('pushState') // 给spy起个名字,方便报错时定位 }, location: { href: 'href', origin: 'origin' } };
2. 在测试模块中配置依赖注入
这部分你已经做对了,再确认下配置位置——要放在TestBed.configureTestingModule的providers数组里,确保组件/服务能拿到这个模拟对象:
beforeEach(async () => { await TestBed.configureTestingModule({ declarations: [YourTargetComponent], // 替换成你的组件类名 providers: [ { provide: 'window', useValue: mockWindowService } ] }).compileComponents(); });
3. 编写测试用例验证调用
现在可以写测试逻辑了,核心思路是:触发组件里调用window服务的方法,然后断言spy是否被正确调用:
it('should call window.history.pushState when navigation is triggered', () => { // 创建组件实例 const fixture = TestBed.createComponent(YourTargetComponent); const component = fixture.componentInstance; // 执行组件里会调用pushState的方法(比如你的组件有个goToPage方法) component.goToPage('/new-url'); // 断言pushState被调用 expect(mockWindowService.history.pushState).toHaveBeenCalled(); // 如果知道预期参数,还可以精准断言 // expect(mockWindowService.history.pushState).toHaveBeenCalledWith(null, '', '/new-url'); });
4. 动态修改模拟属性(比如location.href)
如果需要测试不同的location值对组件的影响,可以在单个测试用例里修改模拟对象的属性:
it('should display correct origin based on window.location', () => { // 修改模拟的origin值 mockWindowService.location.origin = 'https://dev.example.com'; const fixture = TestBed.createComponent(YourTargetComponent); fixture.detectChanges(); // 触发变更检测 // 断言组件渲染了正确的origin const originElement = fixture.nativeElement.querySelector('.origin-display'); expect(originElement.textContent).toBe('Current Origin: https://dev.example.com'); });
小技巧:重置Spy避免测试污染
如果多个测试用例都用到同一个spy,记得在beforeEach里重置它的调用记录,防止测试用例之间互相干扰:
beforeEach(() => { // 重置pushState的调用记录 mockWindowService.history.pushState.calls.reset(); });
针对服务的测试(如果是在服务里注入window)
如果你的window服务是注入到某个服务而非组件里,测试逻辑类似,直接通过TestBed.inject获取服务实例即可:
it('should use window service in business logic', () => { const yourService = TestBed.inject(YourTargetService); yourService.performNavigation(); expect(mockWindowService.history.pushState).toHaveBeenCalled(); });
内容的提问来源于stack exchange,提问作者User 5842
相关产品推荐
相关产品推荐

