You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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结构

  1. 确认TestFeatureSelector对应的feature key:查看reducers文件中TestFeatureSelector的定义,比如如果是这样创建的:

    export const TestFeatureSelector = createFeatureSelector<TestState>('testFeature');
    

    这里的'testFeature'就是该feature在store中的key。

  2. 调整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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.14 17:22:51