N
Nuxt6mo ago
Tirius

Testing custom Module.

Hello. I'm developing a Nuxt module, this module have component that is using composable that import/export data from "#build". Component is working in real app environment. But how can I test this type of component?
// module.ts
addTemplate({
filename: 'ui.options.mjs',
getContents: () => 'export default ' + JSON.stringify(options)
});
addImports({
from: resolve('./runtime/composables/useModuleOptions'),
name: 'useModuleOptions',
as: 'useModuleOptions'
});


// Composable
import uiOptions from '#build/ui.options.mjs';

export const useModuleOptions = () => {
return uiOptions;
}


// MyComponent.vue
<script setup>
const moduleOptions = useModuleOptions();
</script>


// Test
import { mountSuspended } from '@nuxt/test-utils/runtime'
import C from '../../src/runtime/components/MyComponent.vue';

const wrapper = mountSuspended(C);
// module.ts
addTemplate({
filename: 'ui.options.mjs',
getContents: () => 'export default ' + JSON.stringify(options)
});
addImports({
from: resolve('./runtime/composables/useModuleOptions'),
name: 'useModuleOptions',
as: 'useModuleOptions'
});


// Composable
import uiOptions from '#build/ui.options.mjs';

export const useModuleOptions = () => {
return uiOptions;
}


// MyComponent.vue
<script setup>
const moduleOptions = useModuleOptions();
</script>


// Test
import { mountSuspended } from '@nuxt/test-utils/runtime'
import C from '../../src/runtime/components/MyComponent.vue';

const wrapper = mountSuspended(C);
My test throw this error. Error: Failed to resolve import "#imports" from "node_modules/@nuxt/test-utils/dist/runtime-utils/index.mjs". Does the file exist?
1 Reply
Tirius
TiriusOP6mo ago
Look like problem is that mountSuspended is throw the same error even on very basic empty Vue component. mount method from @vue/test-utils is working for component testing but it can't resolve my composable and throw error.
import { mount } from '@vue/test-utils'
import { mount } from '@vue/test-utils'
So the question is the same, how to test this type of components ? I found out that you can resolve '#build' imports by adding resolve option to vitest.config
{
resolve: {
alias: {
'#build/ui.options.mjs': resolve('./test/mocks/ui.options.js'),
},
}
}
{
resolve: {
alias: {
'#build/ui.options.mjs': resolve('./test/mocks/ui.options.js'),
},
}
}
So with that setup I was able to test components using @vue/test-utils, but it was needed to remove composable and use direct import of options in components import moduleOptions from '#build/ui.options.mjs';
Want results from more Discord servers?
Add your server