vendredi 22 janvier 2021

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?

Aucun commentaire:

Enregistrer un commentaire