Search code examples
javascripttypescripttestingmocha.jsrewire

Rewire private Typescript class methods


I'm trying to write unit tests for some private methods in my class using Typescript for my Node.js module. I tried using rewire, but it's unable to access any methods (even public ones). Here is my setup:

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');
    });
});

I tried using rewire on the Typescript file and on the compiled JS file as well, but I get the same error:

ReferenceError: somePrivateMethod is not defined

I'm using Mocha with the following config:

'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",
};

Is there any solution for this problem?


Solution

  • I know is a pretty old question but if someone else find themself in the situation I've managed to find a solutions:

    export class YourClass {
      constructor( ) { }
      
      private thisIsPrivate() {
        //private stuff
      }
      
      otherPublicMethod() {
        //public stuff
      }
    }
    

    inside your test file you can import the class as usual to test public methods

    import YourClass from '../src/classes/YourClass'
    
    const testClass = new YourClass();
    
    ...
    

    to test private methods import the class using rewire

    import rewire from 'rewire'
    
    const rewiredModule = rewire('../src/classes/YourClass')
    
    const rewiredClass = rewiredModule.__get__('YourClass')
    

    then inside your test

    it('Test your private method', function () {
      
       const myRewiredClassInstance = new rewiredClass()
       
       myRewiredClassInstance.thisIsPrivate()
    
       //do your expect here
    }
    

    The only downside is that the object returned is "any" and so no help from typescript.

    you can even debug inside it if you have setup your debugger correctly

    Enjoy everyone