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

如何修剪函数返回的字符串,使其通过单元测试校验?

优先修改函数本身的实现,不要调整测试用例。

问题根因

你当前使用的多行模板字符串会把代码里的换行、缩进原样带入返回结果,导致最终输出的字符串前后包含大量空白、中间也有多余空格,和业务需要的干净时长文本不符。而测试用例的预期值是符合业务需求的正确输出,如果为了适配当前bug修改测试,会让测试失去校验功能,后续函数实际投入使用时,多余空白还会导致前端渲染异常。

修复方案

两种修改方式可按需选择:

方式1:调整模板字符串写法,避免多余空白

直接把拼接逻辑写在同一行,去掉不必要的换行和缩进:

export const getDurationToShow = ({ nDays, descriptive }) => {
    const years: number = Math.floor(nDays / 365);
    const months: number = Math.floor((nDays % 365) / 30);
    const days: number = Math.floor((nDays % 365) % 30) || 0;
    if (!!descriptive) {
        return `${years > 0 ? `${years} year${years > 1 ? 's' : ''},` : ''}${months > 0 ? ` ${months} month${months > 1 ? 's' : ''} ${days > 0 ? 'and' : ''}` : ''}${days > 0 ? ` ${days} days` : ''}`;
    }
    // 非descriptive场景可自行补充默认返回逻辑
}

方式2:保留代码排版,对输出做空白清理

如果觉得多行写法代码可读性更高,可以在返回前对结果做格式化处理:

export const getDurationToShow = ({ nDays, descriptive }) => {
    const years: number = Math.floor(nDays / 365);
    const months: number = Math.floor((nDays % 365) / 30);
    const days: number = Math.floor((nDays % 365) % 30) || 0;
    if (!!descriptive) {
        return `
                ${years > 0 ? `${years} year${years > 1 ? 's' : ''},` : ''} 
                ${months > 0 ? ` ${months} month${months > 1 ? 's' : ''} ${days > 0 ? ' and' : ''}` : ''} 
                ${days > 0 ? `${days} days` : ''}
            `
            .trim()
            .replace(/\s+/g, ' ');
    }
    // 非descriptive场景可自行补充默认返回逻辑
}

补充说明

你给出的调用示例countDays(2000) // 2 years, 9 months and 0 days属于书写错误,按照你现有的计算逻辑,2000天的运算结果为5 years, 5 months and 25 days,和测试用例的预期值一致,不需要调整计算规则。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 11:15:02