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

Angular 2+Ngrx:如何测试Reducer中EnterLocalMode的状态变更

验证Reducer中EnterLocalMode动作的local字段变更测试

咱们先理清楚要完成的测试逻辑:你的Reducer在处理EnterLocalMode动作时,会通过upsertOne把指定id的条目的local字段设为false,所以测试要覆盖修改已有条目和新增条目两种场景,同时确保action的payload正确传递了id。

第一步:补全Action的payload

注意你的Reducer里用到了action.payload.id,所以创建action的时候必须传入目标id,不然找不到要修改的条目。比如:

const action = new MyActions.EnterLocalMode({ id: 'test-pump-id' });

第二步:构造明确的初始状态

为了测试更可靠,最好构造包含目标条目的初始状态(如果是测试新增场景,就用空的初始状态),比如:

// 测试修改已有条目:初始状态里有一个local为true的条目
const initialState = {
  ...MyReducer.initialState,
  commandOne: [
    { id: 'test-pump-id', local: true, /* 其他必要字段 */ }
  ]
};

第三步:添加断言逻辑

调用reducer得到新状态后,找到目标条目,验证它的local字段是否变为false。根据你的commandOne数据结构,断言方式略有不同:

如果commandOne是数组结构:

// 找到目标条目
const targetCommand = state.commandOne.find(cmd => cmd.id === 'test-pump-id');
// 先确保条目存在
expect(targetCommand).toBeDefined();
// 验证local字段
expect(targetCommand.local).toBe(false);

如果commandOne是Immutable Map(或类似键值对结构):

expect(state.commandOne.get('test-pump-id').local).toBe(false);

完整的测试代码示例

describe('EnterLocalMode action', () => {
  it('should set local to false for an existing command', () => {
    // 构造初始状态:已有一个local为true的测试条目
    const initialState = {
      ...MyReducer.initialState,
      commandOne: [
        { id: 'test-pump-id', local: true, name: 'Test Pump' }
      ]
    };

    // 创建带id的action
    const action = new MyActions.EnterLocalMode({ id: 'test-pump-id' });

    // 执行reducer
    const state = MyReducer.reducer(initialState, action);

    // 验证结果
    const targetCommand = state.commandOne.find(cmd => cmd.id === 'test-pump-id');
    expect(targetCommand).toBeDefined();
    expect(targetCommand.local).toBe(false);
  });

  it('should upsert a new command with local: false when id does not exist', () => {
    // 用默认初始状态(无目标条目)
    const initialState = MyReducer.initialState;

    // 创建带新id的action
    const action = new MyActions.EnterLocalMode({ id: 'new-pump-id' });

    // 执行reducer
    const state = MyReducer.reducer(initialState, action);

    // 验证新增的条目
    const newCommand = state.commandOne.find(cmd => cmd.id === 'new-pump-id');
    expect(newCommand).toBeDefined();
    expect(newCommand.local).toBe(false);
  });
});

额外提示

  • 如果你的测试框架是Jest,上面的expect语法完全适用;如果是其他框架,调整断言方法即可。
  • 确保upsertOne的逻辑符合预期:存在则更新,不存在则新增,这也是为什么要加两个测试用例覆盖两种场景。

内容的提问来源于stack exchange,提问作者Snorlax

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 08:21:58