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并不是公共界面的正式一部分。无法访问未导出的模块功能.
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)
| 归档时间: |
|
| 查看次数: |
3438 次 |
| 最近记录: |