3

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?

Wyctus
  • 33
  • 2
  • 4

1 Answers1

3

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

MajinDageta
  • 250
  • 3
  • 14
  • If you don't know... you can "cast" to types: `const datas = rewire_config.__get__('_Config_config_datas') as WeakMap>;` – Markus May 26 '22 at 16:17
  • 1
    But the bigger downside is that you have to use the compiled JS and there is no code coverage detected for the calls by the TS test framework. – Markus May 26 '22 at 16:20
  • Yes i know that we can use the cast but the object will be an any and we are forcing it to be something else, so if the model changes of the function you are using in the future the test will still compile because he doesn't know what that really is. – MajinDageta May 27 '22 at 09:55