Exploring Vue 3's Composition API with a twist:
The store.ts file
import { ref, Ref } from 'vue';
import { defineStore } from 'pinia';
export const useStore = defineStore('store', () => {
const isLoading: Ref<boolean> = ref(true);
function initialize() {
isLoading.value = true;
setTimeout(() => (isLoading.value = false), 3000);
}
return {
initialize,
isLoading,
};
});
Inside the Component.vue file
<script setup lang="ts">
import { useI18n } from 'vue-i18n';
import { storeToRefs } from 'pinia';
import { useStore } from './store';
const { t } = useI18n();
const store = useStore();
const { isLoading } = storeToRefs(store);
</script>
<template>
<wb-button @click="store.initialize()">{{ t('initialize') }}</wb-button>
<p>Loading: {{ isLoading ? 'Yes' : 'No' }}</p>
</template>
Everything seems fine during implementation, but it gets complicated when testing. To simplify things, I mock vue-i18n globally like this:
Creating testSetup.ts file
import { vi } from 'vitest';
vi.mock('vue-i18n', () => ({
useI18n: () => ({
t: (key: string) => key,
d: (key: string) => key,
}),
}));
Unfortunately, things get messy when attempting to mock the store simultaneously as demonstrated in Component.test.ts:
Testing Component.vue
import { it, expect, vi } from 'vitest';
import { mount} from '@vue/test-utils';
import { createTestingPinia } from '@pinia/testing';
import Component from './Component.vue';
const options = {
global: {
plugins: [
createTestingPinia({
createSpy: vi.fn(),
initialState: {
items: [],
},
}),
],
},
};
it('tests are functioning', () => {
const wrapper = mount(Component, options);
expect(wrapper.findComponent(Component)).toBeTruthy();
});
Upon introducing Pinia mocking to the plugin configuration, the vue-i18n mock fails and triggers an error stating
TypeError: $setup.t is not a function
. Various attempts such as using config.global.mocks
or config.global.plugins
have also failed after implementing Pinia mocking in the tests. It appears that the behavior of the config.global
object is somehow altered by @pinia/testing
, making it difficult to troubleshoot.
Package dependencies listed in package.json:
"@pinia/testing": "0.0.16",
"@types/jsdom": "21.1.1",
"@types/node": "18.16.2",
"@vue/test-utils": "2.3.2",
"jsdom": "21.1.1"
"typescript": "~4.8.4",
"vite": "4.3.3",
"vitest": "0.30.1",