DEV Community

Discussion on: The only 3 steps you need to mock an API call in Jest

Collapse
 
zaklaughton profile image
Zak Laughton

Sure! Mocking the post request is exactly the same as mocking the get request, except you'll want to mock the post method:

axios.post.mockResolvedValue({
    data: [
      {
        userId: 1,
        id: 1,
        title: 'My First Album'
      },
      {
        userId: 1,
        id: 2,
        title: 'Album: The Sequel'
      }
    ]
  });
Enter fullscreen mode Exit fullscreen mode

In this case, you'll want the mocked value to be whatever you get back from the real post response. I've found console.log()-ing the response to a real post request a good way to get a response to copy into the code.

If you want the mock to return a dynamic value based on the input, you could instead use axios.post.mockImplementation(...) This will allow you to create a custom function to build a response based on the input given to axios.post(). You can see the full documentation for mockImplementation() here.

I hope this helps!