Node.js/Jest

[Jest] Sample Axios Mock Function

brightlightkim 2022. 4. 16. 03:54
const getMedia = async (mediaId) => (await makeRequest({
  url: `${MEDIA_BASE_URL}/admin/media/${mediaId}`,
  method: 'GET'
})).data

If this is the function that is making the request through the Axios, we can make it with some curry function and Axios innate data of config to make it and return it with Promise.resolve.

const createMockImplementation = ({ contentId, mediaId }) => (config = {}) => {
  if (config.method?.toLowerCase() === 'get' && config.url?.endsWith(`/admin/content/${contentId}`)) {
    return Promise.resolve({
      status: 200,
      data: {
        id: contentId,
        ...mockContentItem1
      }
    }) // getContent
  } else if (config.method?.toLowerCase() === 'post' && config.url?.endsWith(`/admin/content/${contentId}`)) {
    return Promise.resolve({
      status: 200
    }) // saveContent
  } else if (config.method?.toLowerCase() === 'get' && config.url?.endsWith(`/admin/media/${mediaId}`)) {
    return Promise.resolve({
      status: 200,
      data: {
        id: mediaId,
        ...mockMediaItemWithAssets
      }
    }) // getMedia
  } else if (config.method?.toLowerCase() === 'post' && config.url?.endsWith(`/admin/media/${mediaId ? `/${mediaId}` : ''}`)) {
    return Promise.resolve({
      status: 200
    }) // saveMedia
  }
}