Skip to content

Not be able to test persist function in testing #378

Open
@AeliGo

Description

@AeliGo

Clear and concise description of the problem

import { beforeEach, describe, expect, it, vi } from 'vitest'
import { setActivePinia, createPinia } from 'pinia'
import { useThemeStore } from '@/stores/themeStore'
import piniaPluginPersistedstate from 'pinia-plugin-persistedstate'

describe('useThemeStore', () => {
  const setItemFn = vi.fn()
  const getItemFn = vi.fn()

  beforeEach(() => {
    vi.stubGlobal('localStorage', {
      getItem: getItemFn,
      setItem: setItemFn,
      clear: vi.fn(),
    })

    const pinia = createPinia()
    pinia.use(piniaPluginPersistedstate)
    setActivePinia(pinia)
  })

  it('should have "light" as the default theme', () => {
    const store = useThemeStore()
    expect(store.currentTheme).toBe('light')
  })

  it('should change the theme when setTheme is called', () => {
    const store = useThemeStore()
    store.setTheme('dark')
    expect(store.currentTheme).toBe('dark')
  })

  it.skip('should persist the theme in local storage', async () => {
    const store = useThemeStore()
    store.setTheme('dark')
    expect(setItemFn).toHaveBeenCalledWith(
      'theme',
      JSON.stringify({ currentTheme: 'dark' }),
    )
  })
})

localStorage.setItem not be called

Suggested solution

Please provide a way to test persist function

Alternative

No response

Additional context

No response

Validations

Metadata

Metadata

Assignees

No one assigned

    Labels

    ❓ questionFurther information is requested🚧 missing reproductionThis issue is missing a proper reproduction

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions