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?
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' ]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With