问题描述
我正在尝试使用 Typescript 为我的 Node.js 模块为我的类中的某些私有方法编写单元测试。
我尝试使用 rewire
,但它无法访问任何方法(甚至是公共方法)。
这是我的设置:
myclass.ts
class MyClass{
private somePrivateMethod() {
// do something
console.log(42);
}
public somePublicmethod() {
// do something
this.somePrivateMethod();
// do something
}
}
export default MyClass;
test.ts
import { expect } from 'chai';
import rewire from 'rewire';
describe('Test',function () {
describe('#somePrivateMethod()',function () {
const rewired = rewire('../src/myclass.ts');
//const rewired = rewire('../dist/myclass.js');
const method = rewired.__get__('somePrivateMethod');
});
});
我尝试在 Typescript 文件和编译后的 JS 文件上使用 rewire,但出现相同的错误:
ReferenceError: somePrivateMethod is not defined
我正在使用具有以下配置的 Mocha:
'use strict';
module.exports = {
extension: ["ts"],package: "./package.json",reporter: "spec",slow: 75,timeout: 2000,ui: "bdd","watch-files": ["test/**/*.ts"],require: "ts-node/register",};
这个问题有什么解决办法吗?
解决方法
我知道这是一个很老的问题,但如果其他人发现自己处于这种情况,我已经设法找到了解决方案:
export class YourClass {
constructor( ) { }
private thisIsPrivate() {
//private stuff
}
otherPublicMethod() {
//public stuff
}
}
在你的测试文件中,你可以像往常一样导入类来测试公共方法
import YourClass from '../src/classes/YourClass'
const testClass = new YourClass();
...
要测试私有方法,请使用 rewire
导入类
import rewire from 'rewire'
const rewiredModule = rewire('../src/classes/YourClass')
const rewiredClass = rewiredModule.__get__('YourClass')
然后在你的测试中
it('Test your private method',function () {
const myRewiredClassInstance = new rewiredClass()
myRewiredClassInstance.thisIsPrivate()
//do your expect here
}
唯一的缺点是返回的对象是“any”,因此没有 typescript 的帮助。
如果您正确设置了调试器,您甚至可以在其中进行调试
享受每一个人