Skip to content

Testing with a Pinia store best practices #571

@silverbackdan

Description

@silverbackdan

It is described in the Pinia testing to do this for testing with a Pinia store:
https://pinia.vuejs.org/cookbook/testing.html

import { setActivePinia, createPinia } from 'pinia'
import { useCounterStore } from '../src/stores/counter'

describe('Counter Store', () => {
  beforeEach(() => {
    // creates a fresh pinia and make it active so it's automatically picked
    // up by any useStore() call without having to pass it to it:
    // `useStore(pinia)`
    setActivePinia(createPinia())
  })
...

However because my plugin & module created pinia stores, this is too late.

For now, I've adjusted my plugin

import { setActivePinia, createPinia } from 'pinia'
import { addRouteMiddleware, defineNuxtPlugin } from '#app'
import CwaRouteMiddleware from '#cwa/runtime/route-middleware'
import Cwa from '#cwa/runtime/cwa'
import { options } from '#build/cwa-options'

export default defineNuxtPlugin({
  name: 'cwa-plugin',
  enforce: 'pre',
  setup (nuxtApp) {
    if (process.env.NODE_ENV === 'test') {
      setActivePinia(createPinia())
    }
    addRouteMiddleware('cwa', CwaRouteMiddleware, { global: true })
    return {
      provide: {
        cwa: new Cwa(nuxtApp, options)
      }
    }
  },
  hooks: {}
})

So I can set the active pinia store without causing an error when starting the nuxt environment. Is this the preferred way to do this or is there a better DX to be had when testing a module which is using pinia stores?

Metadata

Metadata

Assignees

No one assigned

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions