如何在Angular Jasmine中对sessionStorage进行spyOn测试?
在Angular Jasmine中对sessionStorage进行SpyOn的实现方法
针对你提供的组件逻辑(在ngOnInit中从sessionStorage获取currentUser并解析出role),可以通过以下步骤在Jasmine测试中实现对sessionStorage的SpyOn:
核心实现步骤
- 直接对浏览器全局对象
window.sessionStorage的getItem方法创建Spy,预设返回值以模拟不同场景 - 触发组件的
ngOnInit生命周期钩子,验证逻辑是否符合预期
完整测试代码示例
import { ComponentFixture, TestBed } from '@angular/core/testing'; import { YourComponent } from './your.component'; // 替换为你的组件实际路径 describe('YourComponent', () => { let component: YourComponent; let fixture: ComponentFixture<YourComponent>; beforeEach(async () => { await TestBed.configureTestingModule({ declarations: [YourComponent] }).compileComponents(); }); beforeEach(() => { fixture = TestBed.createComponent(YourComponent); component = fixture.componentInstance; }); it('should initialize role from sessionStorage', () => { // 1. 创建sessionStorage.getItem的Spy,返回模拟的currentUser JSON字符串 spyOn(window.sessionStorage, 'getItem').and.returnValue(JSON.stringify({ role: 'admin' })); // 2. 触发ngOnInit(fixture.detectChanges会触发组件初始化流程) fixture.detectChanges(); // 3. 验证Spy被正确调用,且组件的role属性符合预期 expect(window.sessionStorage.getItem).toHaveBeenCalledWith('currentUser'); expect(component.role).toBe('admin'); }); it('should handle missing currentUser in sessionStorage', () => { // 模拟sessionStorage中不存在currentUser的场景 spyOn(window.sessionStorage, 'getItem').and.returnValue(null); fixture.detectChanges(); // 根据业务逻辑调整预期,比如role为undefined或预设默认值 expect(component.role).toBeUndefined(); }); });
关键说明
- 因为
sessionStorage是浏览器全局对象,直接通过spyOn(window.sessionStorage, 'getItem')即可监听其方法调用 - 通过
and.returnValue预设返回的JSON字符串,确保JSON.parse能正确解析出包含role的对象 fixture.detectChanges()会触发组件的初始化流程,进而执行ngOnInit中的逻辑
内容的提问来源于stack exchange,提问作者Sivaguru Nathan
相关产品推荐
相关产品推荐

