So I wanted to compare the 2 main styles for writing typescript servers and testing the code.
-
Using jest.mock
-
Writing code with dependency injection.
-
Hybried.
( As it seems I am not the only one who compared - https://gist.github.com/ryyppy/e60376024aa9e4fe2962f3ab13e87bf0 )
-
When using jest mock - it allows you to 'replace' packages which are imported into a class/function. This ability allows you to mock and use SPYS for testing in a code without injecting those from the API.
It's easy to write code this way without worring about the testing and hacking your way inside.
For OOP developers it feels like a cheat.
-
This means that you put all dependency injections in the function/constuctor.
It's very easy to test since the function signature shows you all the dependencys and if you used interfaces it's easy to mock 'const myConst : myInterface = jest.mock();'
Writing code using fully dependency injection should be used with an IOC-container - for example http://inversify.io/ this addes to the complexity of your code.
Code looks like Java/c# - some might say it's an advantage some disadvantage.
I suggest the Hybried apparoach (very similar to React best practices), Choose a functions/class that will be your 'Container' that imports everything from the node-modules and from that point use DI to call all other logic. - This will allow you to test your submoduels easily and use the jest.mock hack in one place which is expected- In our express app I would call a 'Controller' the 'Container' and any other code from that point should be called with DI. Example hybried:
\* Controller\"
import handler from ./'handler'
import validator from './validator'
import logger from './logger'
async (req: Request, res: Response) => {
const validationError = validate(req,logger);
if (validationError != null) {
return;
}
handler(logger,req.body,req.file);
res.(200);
return;
So this are my 2 cents of reasearch.