DEV Community

Dhanush N
Dhanush N

Posted on

Node Js - How to write unit test for functions which are completely db driven ??

I need to write test case using jest for a function which is completely db driven, business logics are also db driven. Can I use inmemory storage, or any other ideas ???

Top comments (1)

Collapse
 
huncyrus profile image
huncyrus

Hi,
Valid question, you will face it more and more, when it came for 3rd party tools, database or different services or even abstract modules.
The real question, what you have to ask always from yourself - and from test specification and also ask the task giver - what do you would like to prove? What result you seeking? What's the purpose of the test itself?
I seen many times when I helped interns and juniors they tried to test an entire method what often was a service or something what not really possible to test.

In your case, let me ask: What do you would like to test? The database connection? The business logic? The database operation? The data transform? The data transport? The database endurance?

Usually in such situations people tend to make mocks and hardcoded data.

Use-case (silly, sry):
For creating an user, you have a class 'UserCreationService', what call an 'UserCreationController' and also a model 'UserModel'.
If the task write: 'You have to test the user creation method, and supposed to cover it with unit tests', then it mean, you have to test the 3 entity as individual, which mean, you have to mock the data itself (e.g.: variable with stored hardcoded data what has the exact structure as the original part (e.g.: controller or model)). In the end, you possibly will end up 3+ test case file and dozens of tests per file.

This isn't the best explanation ever, possibly