18 creatableclass - ranhs/soda-test GitHub Wiki

Usally when you want to create instance of a class you need to use the new keyword on the class type, and pass to the constructor the relevant arguments (if needed)

const obj = new MyClass("Me", 17)

If the class is in a private model (your model) or the class is abstruct (or both), you cannot do that.
Soda-Test gives you a generic interface, called CreatableClass. Instance that implemnet this interface is a type of class that can be caleld with new keyword, and be passed the arguments that are defined as the generic types.
For example you have the following private class in class.ts

class MyPrivateClass {
    constructor(name: string, id: number) {...}
    ...
}

You want in you test code to create an instane of this class (to test it)

@ImportPrivate('./class','MyPrivateClass)
MyPrivateClassConstructor: CreatableClass<string, number>

And in the test code the instance can be created the following way:

const instance = new this.MyPrivateClassConstructor("Me", 17)

Notes:

  1. in Soda-Test v 1.0 the CreatableClass supports up to 3 generic types
  2. if you what to specify that an argument to the constructor is optional, in the genic type type write | void for exapmle for constractor(name: string, id?: number) use the type CreatableClass

Abstract classes

The above method, also works on abstract classes, and alows you to create instance of them to be tested. However if the class is not private, you may use a differnt method: ```ts const MyAbstractClassConstructor: CreatableClass = MyAbstractClass as never const instance = new MyAbstractClassConstructor("Me", 17) ```

Skipping the constructor

In some cases you would like to have an instnace of a class to tests its member method, but you don't want it to run the constructor. This can be done the follwoing way:

const instnace: MyTestedClass = {} as never
Object.setPrototypeOf(instance, MyTestedClass.prototype)

It is recomended to put the instance as a member varible of the test-class, and run the above code in beforeEach method, so the instance can be used in each test-step.

If the class is private you need rewire to get its prototype

@rewire('./class')
classRewire: Rewire

private instance: TestedClassDummyInterface

beforeEach(): void  {
    this.instance = {} as never
    Object.setPrototypeOf(this.instance, classRewire.get('TestedClass.prototype')
}

⚠️ **GitHub.com Fallback** ⚠️