javascriptvue.jstestingquasar-frameworkvue-i18n

How to test Quasar boot files?


My boot file connects router with Vue i18n.

src/boot/i18n.js:

import { boot } from 'quasar/wrappers'
import { createI18n } from 'vue-i18n'
import { i18nBootConfig, qDefaultLangPack } from 'src/i18n/config'
import { guessLocale } from 'src/helpers/lang'
import { Lang } from 'quasar'

export default boot(async ({ app, router, ssrContext }) => {
  const i18n = createI18n(i18nBootConfig)
  // Set i18n instance on app
  app.use(i18n)
  Lang.set(qDefaultLangPack)

  router.beforeEach(async (to, _from, next) => {
    await guessLocale({ globalI18n: i18n.global, route: to, ssrContext })
    return next()
  })
})

I wonder how can I test this connection with Vitest?


Solution

  • I got to test it this way:

    import { beforeAll, describe, expect, it, vi } from 'vitest'
    import { createApp } from 'vue'
    import { createMemoryHistory, createRouter } from 'vue-router'
    
    vi.mock('src/helpers/lang', async (importActual) => {
      const actual = await importActual()
      return { ...actual, guessLocale: vi.fn(actual.guessLocale) }
    })
    import { guessLocale } from 'src/helpers/lang'
    import routes from 'src/router/routes'
    
    import i18nBoot from './i18n'
    
    describe(i18nBoot, () => {
      let app, router, i18n
      beforeAll(async () => {
        app = createApp()
        router = createRouter({ history: createMemoryHistory(), routes })
        await i18nBoot({ app, router, ssrContext: null })
    
        i18n = app['__VUE_I18N__']
      })
    
      it('sets locale according to locale route param', async () => {
        await router.push('/es-ES')
        expect(i18n.global.locale.value).toBe('es-ES')
      })
    
      it('calls guess locale', async () => {
        await router.push('/')
    
        const args = guessLocale.mock.lastCall[0]
        expect(Object.keys(args).sort()).toEqual(
          ['globalI18n', 'route', 'ssrContext'].sort()
        )
        expect(args.globalI18n).toBe(i18n.global)
        expect(args.route.path).toBe(router.currentRoute.value.path)
      })
    })