React外卖应用判断嵌套数组配送时段存在性及单元测试实现咨询
配送时段判断解决方案
辅助函数实现
你可以直接用数组的some方法做短路判断,只要找到任意一天存在非空的配送时段就立即返回true,性能更高,也能覆盖你提到的所有场景:
const hasAvailableDeliverySlot = (deliveryArea) => { // 先做边界校验,避免空数据、异常结构导致报错 if (!deliveryArea?.deliverySlots?.length) return false // 遍历所有日期的配送槽位,只要有一个时段数组非空就返回true return deliveryArea.deliverySlots.some(slot => { return Array.isArray(slot.deliveryTimes) && slot.deliveryTimes.length > 0 }) }
如果你还需要额外校验配送时段的有效性(判断validFrom和validUntil是否包含当前时间),可以扩展逻辑如下:
const hasValidDeliverySlot = (deliveryArea) => { if (!deliveryArea?.deliverySlots?.length) return false const nowTimestamp = Date.now() return deliveryArea.deliverySlots.some(slot => { if (!Array.isArray(slot.deliveryTimes) || !slot.deliveryTimes.length) return false // 检查当天是否有在有效期内的时段 return slot.deliveryTimes.some(timeItem => { const from = new Date(timeItem.validFrom).getTime() const until = new Date(timeItem.validUntil).getTime() return nowTimestamp >= from && nowTimestamp <= until }) }) }
单元测试实现
以常用的Jest测试框架为例,你可以覆盖以下核心测试场景:
- 未来7天完全无配送时段 → 返回false
- 任意一天存在配送时段 → 返回true
- 前几天无时段、后续日期有 → 返回true
- 配送槽位数组为空 → 返回false
- 入参为undefined/空对象 → 返回false
测试代码示例:
// 引入你编写的辅助函数 import { hasAvailableDeliverySlot } from './你的工具函数文件路径' // 准备测试数据 // 无配送时段的测试数据 const noSlotData = { deliveryMethod: "PICKUP", deliverySlots: [ { date: "2021-08-04", deliveryTimes: [] }, { date: "2021-08-05", deliveryTimes: [] }, { date: "2021-08-06", deliveryTimes: [] }, { date: "2021-08-07", deliveryTimes: [] }, ], } // 有配送时段的测试数据 const hasSlotData = { deliveryMethod: "PICKUP", deliverySlots: [ { date: "2021-08-04", deliveryTimes: [] }, { date: "2021-08-05", deliveryTimes: [] }, { date: "2021-08-06", deliveryTimes: [] }, { date: "2021-08-07", deliveryTimes: [ { time: "16:30-17:00", validFrom: "2020-08-07", validUntil: "2023-08-07" }, { time: "18:00-19:00", validFrom: "2020-08-07", validUntil: "2023-08-07" }, ], }, ], } // 空槽位测试数据 const emptySlotData = { deliveryMethod: "PICKUP", deliverySlots: [] } // 编写测试用例 describe('hasAvailableDeliverySlot 功能测试', () => { test('全量日期无配送时段返回false', () => { expect(hasAvailableDeliverySlot(noSlotData)).toBe(false) }) test('存在配送时段返回true', () => { expect(hasAvailableDeliverySlot(hasSlotData)).toBe(true) }) test('配送槽位为空返回false', () => { expect(hasAvailableDeliverySlot(emptySlotData)).toBe(false) }) test('入参为undefined返回false', () => { expect(hasAvailableDeliverySlot(undefined)).toBe(false) }) test('入参为空对象返回false', () => { expect(hasAvailableDeliverySlot({})).toBe(false) }) })
配置好Jest环境后直接执行测试命令即可验证函数逻辑是否符合预期。
内容的提问来源于stack exchange,提问作者user12494839
相关产品推荐
相关产品推荐

