To mock the useCookie composable in your Vitest tests for Nuxt, you can use the mockNuxtImport helper provided by Nuxt's test utils. Here's how you can set up your tests for the two scenarios you described:
import { describe, it, expect, beforeEach } from 'vitest'
import { mockNuxtImport } from '@nuxt/test-utils/runtime'
describe('Banner visibility tests', () => {
beforeEach(() => {
vi.restoreAllMocks()
})
it('should not show banner when CookieLayoutBannerTopIsHidden is TRUE', async () => {
mockNuxtImport('useCookie', () => {
return () => ({ value: true })
})
})
it('should show banner when CookieLayoutBannerTopIsHidden is FALSE', async () => {
mockNuxtImport('useCookie', () => {
return () => ({ value: false })
})
})
})
In this setup:
- We import the necessary Vitest functions and the
mockNuxtImport helper.
- We use
beforeEach to reset all mocks before each test, ensuring a clean slate.
- For each scenario, we use
mockNuxtImport to mock the useCookie composable, returning an object with a value property set to either true or false.
Note that mockNuxtImport can only be used once per mocked import per test file, as mentioned in the Nuxt documentation (https://nuxt.com/docs/getting-started/testing#mocknuxtimport). If you need to change the mock implementation between tests, you can use vi.hoisted as described in the documentation.
Remember to implement the actual test logic and assertions based on your specific component and banner implementation.