Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get class methods in typescript

Tags:

typescript

I am running typescript unit tests with mocha chai (after setting the compiler options to ts-node).

In one of my unit tests, I would like to get all the methods of a utility class that I have created and run the same tests on them. To be more concrete, I would like to achieve something like this:

UtilityClass.getMethods().forEach(method=>{method(sameInputData)})

Is there a way to implement getMethods elegantly? Or maybe, another way to tackle this need?

like image 897
tcoder01 Avatar asked Sep 17 '16 08:09

tcoder01


1 Answers

I had a very hard time getting other answers to work. They also don't cover a way to do it without an instance, if that's helpful to you as it was for me.

This is what I came up with:

SomeClass.ts

import { route } from "../../lib/route_decorator";

export class SomeClass {
    index() {
        console.log("here");
    }
}

And somefile.ts

let ctrl = require("./filepath/filename");
// This is because angular exports as `exports.SomeClass = SomeClass;`
ctrl = ctrl[Object.keys(ctrl)[0]];
let ctrlObj = new ctrl();

// Access from Class w/o instance
console.log(Reflect.ownKeys(ctrl.prototype));
// Access from instance
console.log(Reflect.ownKeys(Object.getPrototypeOf(ctrlObj)));

This works, outputting:

[ 'constructor', 'index' ]
[ 'constructor', 'index' ]
like image 165
csga5000 Avatar answered Sep 30 '22 16:09

csga5000