首页 > 解决方案 > 如何对非导出函数进行单元测试?

问题描述

在 JavaScript ES6 模块中,可能有许多小的、易于测试的函数应该被测试,但不应该被导出。如何在不导出模块的情况下测试模块中的函数?(不使用Rewire)。

标签: javascriptecmascript-6jestjses6-modules

解决方案


导出“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()不应在包之外使用,除非是测试。

我已经用了很多年了,我发现它的效果很好。


推荐阅读