Mocking Vue3 getCurrentInstance with vi or jest

February 22, 2023

In this post we’ll learn how to use vi.importActual along with getCurrentInstance.

Prerequisities

  • A project with Vue3 installed

Mocking getCurrentInstance

Let’s say we have a computed property in Vue3 that returns a value using getCurrentInstance, and gets the value from some props, like this:

const someProps = computed(() => {
    return getCurrentInstance()?.vnode?.props?.prop
})

Now we somehow need to build an integration test for this, that tests that App.vue renders correctly. In that case, we probably want to mock getCurrentInstance somehow, since the prop probably doesn’t exist in getCurrentInstance.

And this is how we do that:

describe('App', async () => {
    vi.mock('../../../node_modules/vue/index.mjs', async () => {
        const actual = await vi.importActual('../../../node_modules/vue/index.mjs')
        return {
            ...actual,
            getCurrentInstance: vi.fn(() => ({
                vnode: {
                    ...actual.getCurrentInstance.vnode,
                    props: {
                        someProps: 'returns something'
                    },
                },
            }),
            )}
    })
    const createComponent = () =>  mount(App)

    it('should render App', async () => {
        ...
    })
})

And now our tests will pass.

If you happen to use jest, just change every vi to jest, and it should pass.

Wrapup

In this post we’ve shortly gone through how you can mock getCurrentInstance in Vue3.


Profile picture

Written by An anonymous coder who lives and works building useful things. Mostly focusing on Django, Vue and overall Python examples.