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

如何使用Jest测试Reducer中带有if判断的分支逻辑?

测试包含条件判断的Reducer分支(Jest)

我来帮你拆解这个Reducer的测试逻辑,一步步写清楚每个分支的测试用例——毕竟要覆盖到所有if分支和case,才能确保Reducer的行为符合预期。首先先确认你的Reducer是基于Immutable.js的(因为用到了getIn/setIn方法),所以测试时我们需要用Immutable的工具来构建状态。

前置准备

先导入需要的依赖和文件,把基础环境搭好:

import { fromJS } from 'immutable';
import notificationReducer from './your-reducer-file'; // 替换成你的Reducer实际路径
import { REMOVE_NOTIFICATION, TICK_NOTIFICATION } from './your-action-types'; // 替换成你的action类型文件路径

// 和你的Reducer里保持一致的initialState
const initialState = fromJS({
  notification: {
    message: 'test reminder',
    timer: 5
  }
});

逐个分支编写测试用例

1. 测试REMOVE_NOTIFICATION:消息匹配时返回initialState

这是if判断的第一个分支——当action的message和state里的通知消息一致时,要重置为初始状态。我们可以这样写:

test('REMOVE_NOTIFICATION returns initialState when message matches', () => {
  // 构造一个和state里匹配的action
  const matchAction = {
    type: REMOVE_NOTIFICATION,
    message: 'test reminder'
  };
  
  const newState = notificationReducer(initialState, matchAction);
  
  // 断言返回的状态和初始状态完全一致
  expect(newState).toEqual(initialState);
});

2. 测试REMOVE_NOTIFICATION:消息不匹配时返回原状态

这是if判断的另一个分支——当消息不匹配时,Reducer应该原封不动返回当前状态:

test('REMOVE_NOTIFICATION returns original state when message does not match', () => {
  const mismatchAction = {
    type: REMOVE_NOTIFICATION,
    message: 'unrelated message'
  };
  
  const newState = notificationReducer(initialState, mismatchAction);
  
  // 因为Immutable是不可变数据结构,未修改的状态会和原状态引用相同,用toBe判断更准确
  expect(newState).toBe(initialState);
});

3. 测试TICK_NOTIFICATION:timer值正确减1

这个case是修改timer的数值,我们要验证timer确实减少了1:

test('TICK_NOTIFICATION decrements notification timer by 1', () => {
  const tickAction = { type: TICK_NOTIFICATION };
  
  const newState = notificationReducer(initialState, tickAction);
  
  // 断言新状态的timer是初始值减1
  expect(newState.getIn(['notification', 'timer'])).toBe(4);
});

4. 测试default分支:返回原状态

当传入未知的action类型时,Reducer应该直接返回原状态,不能报错也不能修改状态:

test('default case returns original state', () => {
  const unknownAction = { type: 'RANDOM_UNKNOWN_ACTION' };
  
  const newState = notificationReducer(initialState, unknownAction);
  
  expect(newState).toBe(initialState);
});

一些小提示

  • 因为用了Immutable.js,断言时如果是判断结构一致用toEqual,判断是否是同一个不可变对象引用用toBe,这样更精准。
  • 每个测试用例尽量保持独立,都从初始状态开始测试,避免测试之间的依赖影响结果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 06:36:33