javascript - 如何对非导出函数进行单元测试?
问题描述
在 JavaScript ES6 模块中,可能有许多小的、易于测试的函数应该被测试,但不应该被导出。如何在不导出模块的情况下测试模块中的函数?(不使用Rewire)。
解决方案
导出“exportedForTesting”常量
function shouldntBeExportedFn(){
// Does stuff that needs to be tested
// but is not for use outside of this package
}
export function exportedFn(){
// A function that should be called
// from code outside of this package and
// uses other functions in this package
}
export const exportedForTesting = {
shouldntBeExportedFn
}
以下可用于生产代码:
import { exportedFn } from './myPackage';
这可以用于单元测试:
import { exportedFn, exportedForTesting } from './myPackage';
const { shouldntBeExportedFn } = exportedForTesting;
该策略为我团队中的其他开发人员保留了上下文线索,这些线索shouldntBeExportedFn()
不应在包之外使用,除非是测试。
我已经用了很多年了,我发现它的效果很好。
推荐阅读
- amazon-web-services - 有没有办法查看我使用的所有 AWS 服务的运行成本/免费套餐使用情况?
- python - 在文本文件中插入或删除潜台词
- java - 无法自动装配 MapStruct 映射器
- python - 如何使用 python 将 JSON 转换为数据框
- java - 如何遍历String[],转换为class,获取class字段
- kubernetes - Pod 无法挂载到 Docker Desktop 本地测试环境上的 NFS pod
- wpf - RibbonRadioButton 默认值未在应用程序启动时设置
- javascript - Gradle Build Failed React native: > com.android.builder.errors.EvalIssueException: compileSdkVersion 未指定。请将其添加到 build.gradle
- finance - 以天为单位计算平均加权利率、利率、贷款余额和期限
- reactjs - Vite + TailwindCSS : :focus 不工作