Angular Signal状态管理测试报错:无法读取undefined的userIds属性
问题排查:NgRx Selector测试中出现"Cannot read properties of undefined (reading 'userIds')"
问题现象
测试TestComponent的should create用例时,触发TypeError,提示无法读取undefined的userIds属性,错误定位在createSelector定义的第4行。
错误栈信息
TypeError: Cannot read properties of undefined (reading 'userIds') 2 | import { TestReducers } from '../reducers'; 3 | > 4 | export const getuserIds = createSelector(TestReducers.TestFeatureSelector, state => state.userIds); | ^
相关代码
测试代码
describe('TestComponent', () => { let component: TestComponent; let fixture: ComponentFixture<TestComponent>; let store: MockStore<State>; beforeEach(async () => { await TestBed.configureTestingModule({ declarations: [TestComponent], providers: [ provideMockStore({ initialState: { userIds: '1234' }, }), ], }).compileComponents(); fixture = TestBed.createComponent(TestComponent); store = TestBed.inject(MockStore<State>); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); });
组件使用Selector代码
userId = this.store.selectSignal(getUserIds);
Selector定义
export const getUserIds = createSelector(TestReducers.TestFeatureSelector, state => state.userIds);
问题原因
TestReducers.TestFeatureSelector是NgRx的feature selector,它对应的是store中某个feature slice的根节点。你当前在provideMockStore中直接把userIds放在initialState根节点,导致feature selector返回undefined,进而访问state.userIds时出错。
解决方案
方案1:匹配真实store的state结构
确认
TestFeatureSelector对应的feature key:查看reducers文件中TestFeatureSelector的定义,比如如果是这样创建的:export const TestFeatureSelector = createFeatureSelector<TestState>('testFeature');这里的
'testFeature'就是该feature在store中的key。调整
provideMockStore的initialState,将userIds嵌套在feature key对应的对象中:provideMockStore({ initialState: { testFeature: { // 替换为你的feature key userIds: '1234' } }, })
方案2:直接覆盖Selector的返回值(更简洁)
不需要构造完整的state结构,直接用mockStore.overrideSelector指定selector的返回值:
beforeEach(async () => { await TestBed.configureTestingModule({ declarations: [TestComponent], providers: [provideMockStore()], // 无需initialState }).compileComponents(); fixture = TestBed.createComponent(TestComponent); store = TestBed.inject(MockStore<State>); // 覆盖getUserIds selector的返回值 store.overrideSelector(getUserIds, '1234'); component = fixture.componentInstance; fixture.detectChanges(); });
验证
修改后重新运行测试,should create用例会正常通过,不再触发undefined错误。
内容的提问来源于stack exchange,提问作者Vamshi Kunuguntla
相关产品推荐
相关产品推荐

