Nuxt3 + Cypress: "Usei18N Is Not Defined" Error in Component Testing
I'm Currently Working on Testing Vue Components in Nuxt 3 Using Cypress. I Have a Modal Component (Sharedmodaldefault. Vue) That I'm Trying to Test with the...
I'm currently working on testing Vue components in Nuxt 3 using Cypress. I have a modal component (SharedModalDefault.vue) that I'm trying to test with the following Cypress code:
import SharedModalDefault from "/components/Shared/Modal/SharedModalDefault.vue"
describe('Modal Component Test', () => {
it('should render a modal with default props', () => {
cy.mount(SharedModalDefault, {
props: {
show: true,
title: 'Modal Title',
text: 'Modal Text',
size: 'xl',
},
})
cy.get('[role="dialog"]').should('exist')
})
})
However, when I run this test, I'm encountering the following error:
useI18n is not defined
I've double-checked that vue-i18n is properly installed in my project and set up in nuxt.config.js. The module is working properly in my component using const {t} = useI18n() without a specific import.
Is there something I'm missing in the setup or is there a specific configuration needed for vue-i18n in Cypress tests with Nuxt3?
Any help or guidance on resolving this issue would be greatly appreciated.
Thank you!
Update
When I add useI18n to the window, it supresses the error:
cy.window().then((win) => {
win.useI18n = () => ({
t: (key: string) => key, // Mocking the t function
})
})
However, this will jump to the next one: useSlots(), then to computed(), and so on.
What is the proper way to deal with these auto imports?
1 Answer
Try following the Vue example at Replicating plugins
The docs say there isn't yet support for Nuxt3, but you could get some functionality testing by adding the libraries into a custom cy.mount() as shown.
This is in cypress/support/component.js which is the test equivalent to main in your app.
import { createPinia } from 'pinia' // or Vuex
import { createI18n } from 'vue-i18n'
import { mount } from 'cypress/vue'
import { h } from 'vue'
// We recommend that you pull this out
// into a constants file that you share with
// your main.js file.
const i18nOptions = {
locale: 'en',
messages: {
en: {
hello: 'hello!',
},
ja: {
hello: 'こんにちは!',
},
},
}
Cypress.Commands.add('mount', (component, ...args) => {
args.global = args.global || {}
args.global.plugins = args.global.plugins || []
args.global.plugins.push(createPinia())
args.global.plugins.push(createI18n())
return mount(() => {
return h(VApp, {}, component)
}, ...args)
})