NagRock / ts-mockito

Mocking library for TypeScript
MIT License
978 stars 93 forks source link

Mocking new object creation #187

Closed ghsatpute closed 4 years ago

ghsatpute commented 4 years ago

I have a code which I want to test as below

private method1(...) {
    return new Promise((resolve, reject) => {
        if (!Utils.field) {
            Utils.field = new ThirdPartyClass();
        }
   }
}

I want to mock new ThirdPartyClass() instance creation? How do I do that in TypeScript Mockito?

NagRock commented 4 years ago

Hey, there is no possibility to do that. You can create ThirdPartyClassFactory with create method and mock this create method. But mocking new is not possible.

ghsatpute commented 4 years ago

I think it would be a great addition. There can be many new instance creations and we cannot keep creating a factory for each one.

Also, I, personally, don't like my main code to change because I cannot write test cases.

NagRock commented 4 years ago

But there is no way to override new in JS. Only test runners like jest can do that during code analyze / transpilation. ts-mockito is just runtime lib and cannot change how JS works.