Unit testing Vue component that fetches data and sends to component as prop

Viewed 27

This Vue3 component contains a service that fetches an array of workshops from the database and passes this array as a prop to its child component(s). I want to make sure that the data is the expected data and in the expected form. How might I test this? If I mock this data, I wouldn't get that assurance. Here is my component WorkshopsView:

<script setup lang="ts">
import { useGetWorkshops } from '@/services/useGetWorkshops'
import WorkshopsGrid from '@/components/WorkshopsGrid.vue'

const { data: workshops, error: workshopsError } = useGetWorkshops()
</script>
<template>
  <div>
    <WorkshopsGrid :workshops="workshops" :workshopsError="workshopsError" />
  </div>
</template>

Here is the service useGetWorkshops:

import axios from 'axios'
import useSWRV from 'swrv'

const useGetWorkshops = () =>
  useSWRV('workshops', async () => {
    const response = await axios.get(`/api/workshops`)
    if (response.data.error) {
      return null
    }

    return response.data.data
  })

export default useGetWorkshops

Here is my Jest test file for WorkshopsView so far:

import { shallowMount } from '@vue/test-utils'
import WorkshopsView from '@/components/WorkshopsView.vue'
import WorkshopsGrid from '@/components/WorkshopsGrid.vue'
import useGetWorkshops from '@/services/useGetWorkshops'

jest.mock('@/services/useGetWorkshops', () => {
  return jest.fn().mockImplementation(() => {
    return { data: [], error: null }
  })
})

describe('WorkshopsView', () => {
  it('calls the child component', () => {
    const wrapper = shallowMount(WorkshopsView)
    expect(wrapper.findComponent(WorkshopsGrid).exists()).toBe(true)
  })

  it('calls the service to fetch the data', () => {
    const wrapper = shallowMount(WorkshopsView)
    expect(useGetWorkshops).toHaveBeenCalled()
  }
}

How might it be tested that the component is getting the right data in the expected form to pass to the child component as a prop?

0 Answers
Related