How can i test useElementVisibility with Vitest?

213 Views Asked by At

I have a very simple component (below) that works just fine and i need to test this same component via Vitest + Testing Library, but the useElementVisibility simply doesn't trigger when rendered on tests.

Without the trigger from useElementVisibility my test will never perform the request and my tests can't be written properly.

<script setup lang="ts">
import { computed, ref, watch } from 'vue'

import { useElementVisibility } from '@vueuse/core'

import { useDataCommandStore } from '@/stores/data/dataCommand'

const dataCommandStore = useDataCommandStore()

const target = ref(null)
const targetIsVisible = ref(useElementVisibility(target))


watch(targetIsVisible, () => {
  if (targetIsVisible.value) {
    dataCommandStore.listDataCommands()
  }
})

const response = computed(() => dataCommandStore.dataCommands)
</script>

<template>
  <section>
    <div v-if="res">
      <ResourceCard
        v-for="cmd in res.values"
        :key="cmd._id"
        :resource="cmd"
      />
    </div>
  </section>
  <div id="dummy" ref="target" data-testid="dummy" />
</template>

I tried to focus the element but doesn't work at all.

// Test
describe('DC', () => {
  const fetchMock = vi.spyOn(global, 'fetch')

  beforeEach(() => {
    fetchMock.mockReturnValue(mockResolveData(MOCK_DATA_COMMAND))
    render(DC)
  })

  afterEach(() => {
    fetchMock.mockClear()
  })

  it('should render first test', async () => {
    await fireEvent.focus(screen.getByTestId(/dummy/i))

    const addDC = await screen.findByText(/Add new Data Command/i)
    expect(addDC).toBeInTheDocument()
  }
})

// Render Options
const opt = {
  global: {
    directives: {
      maska: vMaska,
    },

    plugins: [i18n, vuetify, router],
    stubs: ["FontAwesomeIcon"],
  },
}

// vitest.setup.ts
import '@testing-library/jest-dom'
import '@vueuse/core'

import { createPinia, setActivePinia } from 'pinia'

import { beforeEach } from 'vitest'

global.CSS = { supports: () => false } as never

beforeEach(() => {
  setActivePinia(createPinia())
})
0

There are 0 best solutions below