Tangible Bytes

A Web Developer’s Blog

Vitest Partial Mock InertiaJs

I have a Laravel project using vite InertiaJS and React

A unit test calling the Head module from @inertiajs/react

Was triggering this error

Cannot read properties of undefined (reading 'createProvider')

For this test I don’t really care about the Head module - but didn’t want to try and mock the whole of inertia-react

I order to partially mock I did this

vi.mock('@inertiajs/react', async () => {
    const originalModule = await vi.importActual('@inertiajs/react')

    return { ...originalModule, Head: ({ title }) => <div data-testid="head">{title}</div> }
})

see https://vitest.dev/api/vi#vi-importactual

Now my test works 🎉