DEV Community

Md. Asif Rahman
Md. Asif Rahman

Posted on

Jest Mocking: Behind the scene

Jest is a famous javascript testing framework built on top of jasmine and maintained by Meta.

While writing unit tests or integration tests we need to mock several functions that calls api or persists data to database.

In this article, I will share how mock functions work behind the scene or the implementation of jest mock method i.e.

fn()
Enter fullscreen mode Exit fullscreen mode

So, if you have used jest in any of your JS project, I can be sure that you have mocked any long running functions using fn() or spyOn() functions of jest.

Now, I am going to reveal the implementation of the fn() function itself.

Problem Statement:
For example, we need to fetch post data from json placeholder and slugify the title of the retrieved post.

So, for this we need to write the following functions:

  1. Retrieve the post data
let getPost = async ()=>{
  const response = await fetch('https://jsonplaceholder.typicode.com/todos/1');
  const post = await response.json();
  return post;
}
Enter fullscreen mode Exit fullscreen mode
  1. Slugify the retrieved post's title:
const slugifyTitle = async () =>{
  const postToSlugify = await getPost();
  return postToSlugify.title.toLowerCase().replace(/ /g,'-').replace(/[^\w-]+/g,'');
}

Enter fullscreen mode Exit fullscreen mode

Now, if we want to run the function, it will actually hit the api endpoint and network call.

slugifyTitle().then(response => {
  console.log(response) // delectus-aut-autem
})
Enter fullscreen mode Exit fullscreen mode

Let's see how to mock the getPost() function to escape the api call. So, first we need to write a function that mocks the getPost function.

const fn = (functionToBeMocked) => {

  const mockFn = (...args) => {
    mockFn.mock.calls.push(args)

    return functionToBeMocked(...args)
  }

  mockFn.mock = { calls: [] }

  return mockFn
}
Enter fullscreen mode Exit fullscreen mode

Now, let's mock the getPost function using fn().

So, now we want out getPost function to get the following data:

const mockedData = {title:'my mocked title'}
getPost = fn(()=>mockedData)
Enter fullscreen mode Exit fullscreen mode

Now, if we call slugifyTitle() function, it will not hit api/network call rather it returns the data we want:

slugifyTitle().then(response => {
  console.log(response) // my-mocked-title
})
Enter fullscreen mode Exit fullscreen mode

So, we can conclude that making mock function is that easy and a simple concept.

In this blog, I just tried to show the basic mechanism of mocking functions in jest or other testing libraries but definitely the real fn() function in jest is not that small.

Top comments (0)