【发布时间】:2021-09-11 05:30:11
【问题描述】:
问题
- 访问模块中的所有 JavaScript/TypeScript 函数以进行单元测试的正确/可接受的方式是什么?
- 我不应该只导出所有函数是否有(充分的)理由?
上下文
请原谅我的无知;我的大部分职业生涯都在使用测试驱动开发 (TDD) 方法编写 Python 代码。现在,我发现自己正在学习 ReactJS/TypeScript 并弄清楚如何实现单元测试,但我很快发现只有导出函数才能访问它们。大多数人都知道,Python 是非常宽松的。确实没有隐私的概念,因此只需导入模块并尊重您可以访问的内容。但 JavaScript 只导入已显式导出的模块的功能,因此提供了适度的障碍。
有人告诉我,导出所有函数进行测试不是一个好主意,但我不知道有另一种方法可以实际测试它们。
示例
我被告知的是“正确/更好”:
Sample1.js:
const func1 = () => {
//code that does stuff
return "stuff";
};
const func2 = () => {
//code that does other stuff
return "otherStuff";
};
export { func1 };
Sample1.test.js:
// executed via Jest framework
import * as sample from "./Sample1.js"
describe("Unit Tests for Sample1", () => {
test("Unit Test - func1", () => {
// code that tests stuff
};
test("Unit Test - func2", () => {
// can't test func2 because it's not exported
};
};
为了能够测试所有功能,我正在做什么:
Sample2.js:
const func1 = () => {
//code that does stuff
return "stuff";
};
const func2 = () => {
//code that does other stuff
return "otherStuff";
};
export { func1, func2 };
Sample2.test.js:
// executed via Jest framework
import * as sample from "./Sample2.js"
describe("Unit Tests for Sample2", () => {
test("Unit Test - func1", () => {
// code that tests stuff
};
test("Unit Test - func2", () => {
// code that tests other stuff because it's exported
};
};
记录在案
我专门在 Internet 和 Stack Overflow 上查看了标准和最佳实践,但我没有找到太多可以回答这个特定问题的内容。我找到的最接近的是this SO question,但这并不是我真正想要的。
【问题讨论】:
标签: javascript typescript tdd standards