How to access mock store value in the Vue component when doing jest unit testing? #920
-
I encountered unexpected issue when doing jest unit test. // UserInfo.spec.ts
it('Check user info', async () => {
const wrapper = mount(FeedbackDialog, {
global: {
plugins: [createTestingPinia()],
},
});
const store = userStore();
store.userAuthenticated = true;
store.userInfo = {
userId: 'aaaa1234',
username: 'aaaa1234',
initials: 'AA',
email: 'test@test.com',
completeUserOnboard: true
};
console.log(store.userInfo); // It prints user info object correctly
await wrapper.vm.$nextTick();
expect(wrapper).toBeTruthy();
expect(wrapper.vm.userinfoUrl).toContain('user_id=aaaa1234');
}); In my Vue SFC file, I have something like this: // UserInfo.vue
<script lang="ts" setup>
import { UserInfo } from 'src/models/models';
import { userStore } from 'src/pinia/user-store';
import { computed} from 'vue';
const piniaUserStore = userStore();
const userInfo = computed(() => piniaUserStore.userInfo as UserInfo);
console.log(userInfo.value); // Every attribute in the user info object is empty
const eventLink = encodeURIComponent(window.location.origin + window.history.state.back);
const userinfoUrl= `user_id=${userInfo.value.userId}&username=${userInfo.value.username}
&user_email=${userInfo.value.email}&event_link=${eventLink}`;
</script> I pass mock user data into pinia mock store in the unit test, and I can print out user info object correctly in the test. However, it seems the mock user info data cannot pass to Vue SFC so that my test is always failed since user_id is an empty string. My question is how I pass mock store data into Vue SFC when doing testing? Thanks. |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 3 replies
-
The best would be to pass initial state to https://pinia.vuejs.org/api/interfaces/pinia_testing.TestingOptions.html#initialstate when creating the testing pinia |
Beta Was this translation helpful? Give feedback.
-
Shouldn't const userinfoUrl= computed(() => `user_id=${userInfo.value.userId}&username=${userInfo.value.username}
&user_email=${userInfo.value.email}&event_link=${eventLink}`); |
Beta Was this translation helpful? Give feedback.
The best would be to pass initial state to https://pinia.vuejs.org/api/interfaces/pinia_testing.TestingOptions.html#initialstate when creating the testing pinia