Skip to content

Commit

Permalink
feat: include the mocks in component globalThis
Browse files Browse the repository at this point in the history
  • Loading branch information
jrutila committed Jul 3, 2023
1 parent ba53cfb commit 5a09b47
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 0 deletions.
2 changes: 2 additions & 0 deletions src/createInstance.ts
Original file line number Diff line number Diff line change
Expand Up @@ -228,6 +228,8 @@ export function createInstance(
this.$.setupState[k] = v
// eslint-disable-next-line no-empty
} catch (e) {}
//@ts-ignore Setting an unknown global variable for the component instance
globalThis[k] = v
}
// also intercept the proxy calls to make the mocks available on the instance
// (useful when a template access a global function like $t and the developer wants to mock it)
Expand Down
16 changes: 16 additions & 0 deletions tests/components/ScriptSetupWithGlobalFunction.vue
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
<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>
</template>
14 changes: 14 additions & 0 deletions tests/mountingOptions/mocks.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { describe, expect, it, vi } from 'vitest'
import { mount, RouterLinkStub } from '../../src'
import { defineComponent } from 'vue'
import ScriptSetupWithI18n from '../components/ScriptSetupWithI18n.vue'
import ScriptSetupWithGlobalFunction from '../components/ScriptSetupWithGlobalFunction.vue'
import ComponentWithI18n from '../components/ComponentWithI18n.vue'

describe('mocks', () => {
Expand Down Expand Up @@ -90,6 +91,19 @@ describe('mocks', () => {
expect(wrapper.text()).toContain('mocked')
})

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')
})

it('mocks a global function in an option component', () => {
const wrapper = mount(ComponentWithI18n, {
global: {
Expand Down

0 comments on commit 5a09b47

Please sign in to comment.