How to Mock Nested Functions with Jest in Node.js

preview_player
Показать описание
---

Visit these links for original content and any more details, such as alternate solutions, latest updates/developments on topic, comments, revision history etc. For example, the original title of the Question was: Mocking nested functions with jest

If anything seems off to you, please feel free to write me at vlogize [AT] gmail [DOT] com.
---

Understanding the Problem

Consider the following scenario: you have a function that interacts with a database, fetching organisations. The function makes various calls, which include initializing a repository and then getting organisations data from it. During testing, we want to avoid actually executing these database calls. Instead, we need to mock these calls so that our tests can focus on the functionality, rather than the underlying database logic.

The initial code that poses this challenge is as follows:

[[See Video to Reveal this Text or Code Snippet]]

Step-by-Step Solution

Step 1: Mock the Module

First, you need to mock the Repositories module which houses the functions you want to mock.

[[See Video to Reveal this Text or Code Snippet]]

This line tells Jest to automatically mock the Repositories module.

Step 2: Mock the initRepo Function

Since initRepo() does not return any useful value and is already mocked, you don't need to mock it again. Jest takes care of it automatically.

Step 3: Mock the getOrganisationsRepo Function

Next, you need to set up mocking for getOrganisationsRepo to return an object that contains the method getOrganisations. This method needs to be mocked to return a predefined dataset.

[[See Video to Reveal this Text or Code Snippet]]

Step 4: Setting Up the Test

With the mocks in place, you can proceed to write the test ensuring that the getOrganisations function behaves as expected.

[[See Video to Reveal this Text or Code Snippet]]

Step 5: Testing Results

Once you've written your test, running it should lead to results indicating success, which means your mocking setup is working perfectly.

[[See Video to Reveal this Text or Code Snippet]]

Final Notes

Conclusion

Happy Testing!
Рекомендации по теме
visit shbcf.ru