测试未导出的TypeScript函数

mic*_*kov 6 javascript mocha.js chai typescript

我使用Mocha/Chai测试JavaScript前端代码,现在我们切换到TypeScript.我有几个我想测试的功能.但它们不应该是可出口的.我是否可以访问此功能并测试它而无需添加export它们?

blu*_*e10 14

虽然不可能直接访问非导出函数,但仍然有一种方法可以以“半隐藏”方式导出它们。一种可能的方法是:

// In your library module declare internal functions as non-exported like normal.
function someInternalFunctionA(x: number): number {
  return x;
}

function someInternalFunctionB(x: number): number {
  return x;
}

// At the bottom, offer a public escape hatch for accessing certain functions
// you would like to be available for testing.
export const _private = {
  someInternalFunctionA,
  someInternalFunctionB,
};
Run Code Online (Sandbox Code Playgroud)

在测试方面你可以这样做:

import { _private } from "./myModule";

test("someInternalFunctionA", () => {
  expect(_private.someInternalFunctionA(42)).toEqual(42);
});
Run Code Online (Sandbox Code Playgroud)

我喜欢这种方法的地方:

  • 无需直接someInternalFunctionA标记export
  • 很明显,下面的内容_private并不是公共界面的正式一部分。

  • @Teodoro当然,这不是一个很好的解决方案,但从务实的角度来看:(1)导出私有符号的代码是一种非常小的形式“在生产中运行测试代码”,(2)这从来没有造成麻烦在我在现实生活中从事的项目中,(3)测试更细粒度的内部函数的可能性无疑帮助我们交付了正确的代码。 (2认同)

Rom*_*nev 7

无法访问未导出的模块功能.

module MyModule {
    function privateFunction() {
        alert("privateFunction");
    }
}
MyModule.privateFunction(); // Generates a compiler error
Run Code Online (Sandbox Code Playgroud)

但是,不考虑私有方法测试的有效性问题,这是您可以做的.

将您的函数分组到实用程序类中,然后利用可以通过方括号表示法访问私有类成员的事实.

module MyModule {
    export class UtilityClass {
        private privateFunction() {
            alert("privateFunction");
        }   
    }
}
var utility = new MyModule.UtilityClass();
//utility.privateFunction(); Generates a compiler error
utility["privateFunction"](); // Alerts "privateFunction"
Run Code Online (Sandbox Code Playgroud)