如何为含三元运算符的switch case编写Jest单元测试?
问题描述
我已经为下面的switch case函数编写了部分测试用例,但不清楚如何编写包含三元运算符的测试场景。
待测试函数
export function getFormName(type, uppercase, t) { switch (type) { case "withdrawal": return uppercase ? _.upperCase("withdrawal") : "withdrawal"; case "closure": return uppercase ? _.upperCase("closure") // .upperCase 来自 lodash : "closure"; default: return uppercase ? _.upperCase(type) : toTitleCase(type); // toTitleCase 返回首字母大写的字符串 } }
已编写的部分测试代码
import _ from "lodash"; import { toTitleCase } from "utils"; // toTitleCase 返回首字母大写的字符串 describe("utils/helpers", () => { describe("getFormName()", () => { it("should return withdrawal", async() => { const value = "withdrawal"; const result = _.upperCase(value); expect(result).toEqual("WITHDRAWAL"); }); }); });
解决方案
要覆盖函数里的三元运算符逻辑,关键是给每个type分支都分别测一遍uppercase为true和false的情况,同时还要覆盖default分支的两种场景。下面是完整的测试用例:
import _ from "lodash"; import { getFormName } from "utils/helpers"; // 导入待测试的函数 import { toTitleCase } from "utils"; // 模拟toTitleCase实现,避免依赖其内部逻辑 jest.mock("utils", () => ({ ...jest.requireActual("utils"), toTitleCase: jest.fn((str) => str.charAt(0).toUpperCase() + str.slice(1)) })); describe("utils/helpers", () => { describe("getFormName()", () => { // 测试withdrawal分支 describe("当type为'withdrawal'时", () => { it("uppercase为true时返回大写的'WITHDRAWAL'", () => { const result = getFormName("withdrawal", true); expect(result).toEqual("WITHDRAWAL"); }); it("uppercase为false时返回小写的'withdrawal'", () => { const result = getFormName("withdrawal", false); expect(result).toEqual("withdrawal"); }); }); // 测试closure分支 describe("当type为'closure'时", () => { it("uppercase为true时返回大写的'CLOSURE'", () => { const result = getFormName("closure", true); expect(result).toEqual("CLOSURE"); }); it("uppercase为false时返回小写的'closure'", () => { const result = getFormName("closure", false); expect(result).toEqual("closure"); }); }); // 测试default分支 describe("当type不是'withdrawal'或'closure'时", () => { const testType = "deposit"; it("uppercase为true时返回大写的'DEPOSIT'", () => { const result = getFormName(testType, true); expect(result).toEqual(_.upperCase(testType)); }); it("uppercase为false时返回首字母大写的'Deposit'", () => { const result = getFormName(testType, false); expect(result).toEqual("Deposit"); expect(toTitleCase).toHaveBeenCalledWith(testType); }); }); }); });
测试说明
- 每个分支(
withdrawal/closure/default)都分别验证uppercase两种取值下的返回结果,确保三元运算符的两个分支都被覆盖到。 - 针对
default分支,当uppercase为false时,不仅要检查返回的首字母大写结果,还要确认toTitleCase函数被正确调用了。 - 用jest mock来模拟
toTitleCase的实现,这样测试就不用依赖它的内部逻辑,结果更稳定。
内容的提问来源于stack exchange,提问作者shanky
相关产品推荐
相关产品推荐

