-
Notifications
You must be signed in to change notification settings - Fork 269
Open
Labels
Description
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.