DEV Community

Discussion on: Testing with Jest & async/await

Collapse
 
zyabxwcd profile image
Akash • Edited

Disclaimer: I am really new to testing (like its my day 3 of learning unit testing with Jest), so please bear with me if I am misinformed or confused, I am feeling pretty dizzy by all the reading on Jest unit testing. Thanks in advance :)

The product model and service you have used in the seeding data section, they are mocks right? They are not actually interacting with the DB? If there are, isn't that against a unit test and makes it an integration test? Secondly, if they are mocks, how exactly are you managing to get the same record using getById as the one you are creating with the model function? Is there any way that for a single test case, the record that is created by the mocked "productModel.create" will be the one returned by "productService.getById"? I would like to avoid hardcoding initialisation data, like I mean I would not want the record to be same for each of the test case and therefore mock implementation for productModel.create and productService.getById like below is not to my liking.
const data = { name: 'Jon Doe' };
productModel.create = jest.fn().mockResolvedValue(data);
productService.getById = jest.fn().mockResolvedValue(data);

Would we have to like create a mock class with the instance variable storing the record and the class will have one getter and one setter to operate on the same data. We can then assign the mocks of productModel.create to the setter and productService.getById to the getter. This way, maybe we can somehow manage different mock data, created at will to our liking without conflicts cause instance variable will differ per class instance we create. Is this even a good approach to follow or is this an anti-pattern/bad-way and interacting with the actual DB as a trade-off for the complexity of the above approach much more likeable?

I hope I am making sense.