首页 > 解决方案 > 重新连接私有 Typescript 类方法

问题描述

我正在尝试为我的 Node.js 模块使用 Typescript 为我的类中的一些私有方法编写单元测试。我尝试使用rewire,但它无法访问任何方法(甚至是公共方法)。这是我的设置:

我的班级.ts

class MyClass{
    private somePrivateMethod() {
        // do something
        console.log(42);
    }

    public somePublicMethod() {
        // do something
        this.somePrivateMethod();
        // do something
    }
}

export default MyClass;

测试.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",
};

这个问题有什么解决办法吗?

标签: javascripttypescripttestingmocha.jsrewire

解决方案


我知道这是一个很老的问题,但如果其他人发现自己处于这种情况,我已经设法找到解决方案:

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
}

唯一的缺点是返回的对象是“任何”,因此打字稿没有帮助。

如果您正确设置了调试器,您甚至可以在其中调试

享受每个人


推荐阅读