Skip to content

Feature request: global.mocks to also mock into the script setup, not just the template #2119

@jrutila

Description

@jrutila

I am coding with Nuxt and would like to component test following component:

<script setup lang="ts">
import { ref } from 'vue'
const hello = ref('hello')

function clicked() {
  //@ts-ignore For example Nuxt will inject these kinds of global functions
  $fetch('http://www.example.com').then((response : any) => {
    hello.value = response.data
  })
}

</script>

<template>
  <button @click="clicked">{{ hello }}</button>
  <!-- this emulates components that use a global function like $t for i18n -->
  <!-- this function can be mocked using global.mocks -->
</template>

The problem is the $fetch call that is with Nuxt freely available to use in the component. I would like to mock the $fetch method.

The test would then be like this:

  it('mocks a global function used in a script setup', async () => {
    const wrapper = mount(ScriptSetupWithGlobalFunction, {
      global: {
        mocks: {
          $fetch: async (url) => ({ data: 'mocked' })
        }
      }
    })
    expect(wrapper.text()).toContain('hello')
    await wrapper.find('button').trigger('click')
    expect(wrapper.text()).toContain('mocked')
  })

The solution would be that when I mock the $fetch it will become available also in the script setup. At the moment it is only available to use in the template code.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions