JavaScript Testing (JEST)
We learn about Jest and mocks here
What is Mocking?
Let's say in our app, we need to call an API. loadTitle is a function that calls fetchData function. fetchData function is placed in http.js file. fetchData function then calls axios package and this axios has .get method that calls API and returns the data.
fetchData function gets back that data and extracts the title in it and sends it back to it's caller who is loadTitle. loadTitle function converts this title into upper case (transformed text is sent back) and sends it back.

Now let's say we are writing a test to test if loadTitle() returns properly transformed upper case text. But when we test this, we need to call loadTitle which in turn calls fetchData which then calls axios.get() and makes an API request.
For testing our loadTitle function we need to avoid somehow calling API. Let's step back and think what can be done. Let's answer this question, what if loadTitle gets the data from fetchData is not the data coming from the API! That's still Ok right as we don't care from where the data is coming back into loadTitle function. All we care about in the test is whether or not the loadTitle test is passing or not, meaning if loadTitle function is able to convert the data coming from fetchData to upper case or not.
So we have two options here.
We can either make fetchData function return a mocked data back to loadTitle instead of fetchData reaching axios
The second option is to make axios.get() return the mocked data instead of axios.get() calling an API
How to Mock
Mocking fetchData function

So in option 1, we mock the fetchData function placed inside http.js file. How to do that?
Create a __mocks __ folder and add
http.jsfile inside it. This is the file where the original fetchData function is exported.Write a mocked function to return what you want
Inside the test, place this code jest.mock('./http.js')
Now the mocked fetchData is called
Mocking axios package (basically mocking axios.get() function to be specific)

In option 2, we mock the axios.get function. How to do that?
Inside the __mocks__ folder create the file with the package name you need to mock, axios.js in this case. So the file will be axios.js
Write a function here called get() and export it. Make sure it returns a promise like below

You can also make this function async so that it returns a promise by default so that you don't have to use Promise.resolve but straight away return the object.

Now the test runs without jest.mock as, when it hits the axios package, it looks at mocks folder and automatically picks that up
Code

I couldn't add this to my git repo as this is done on my office laptop and it takes more time to set git on this. Hence I've placed all the files above. If you want to see the project then go the my office mac here
/Users/samarnath/Documents/TestCode/js-testing-introduction
Last updated
Was this helpful?