Skip to main content

通过对象间接输入

项目中,全局的配置对象是非常常见的。

比如下面代码读取了全局配置对象上的属性来进行相应输出。

// config.js
export const config = {
allowTellAge: true,
age: 18,
getAge() {
return 18;
},
};
// age.ts
import { config } from "./config";

export function tellAge() {
if (config.allowTellAge) {
return 18;
}
return "就不告诉你";
}

export function isLegalAdult() {
return config.getAge() > 18 ? "Yes" : "No";
}

如果要测试使用了 config 里的属性的 tellAge 函数,可以直接修改 config 里的属性值来测试不同的情况。

如果测试使用了 config 里的方法的 isLegalAdult 函数,做法也是直接修改方法即可:

describe("通过对象间接输入", () => {
it("属性", () => {
config.allowTellAge = false;
const r = tellAge();
expect(r).toBe("就不告诉你");
});

it("方法", () => {
config.getAge = () => {
return 2;
};
const r = isLegalAdult();
expect(r).toBe("No");
});
});