Here my code :
A random component :
watch: {
'notifications' : {
handler(newVal) {
let questionnaireTypes = ['TwoDaysConnected', 'OneWeekConnected', 'TwoWeekInactive']
if(newVal) {
this.checkDisplayQuestionnaire(questionnaireTypes)
}
},
immediate: false
}
},
The method in mixin_common.js :
import EventBus from "./event-bus.js"
export default window.mixin_common = {
methods: {
checkDisplayQuestionnaire(questionnaireTypes) {
let stateNotifications = this.$store.state.notifications
EventBus.$emit('openQuestionnaireExperimentationModalWithDatas',
stateNotifications)
}
}
The component where is the modal i want to open with the EventBus :
import EventBus from "./event-bus.js"
methods: {
openModal() {
this.$bvModal.show('questionnaireExperimentationModal')
},
},
mounted() {
EventBus.$on('openQuestionnaireExperimentationModalWithDatas', (notifications) => {
this.notifications = notifications
this.openModal()
})
Event-bus.js :
import Vue from 'vue'
const EventBus = new Vue();
export default EventBus;
Actually, the modal does not open, the only way it works is when i place the EventBus.$emit('openQuestionnaireExperimentationModalWithDatas', stateNotifications) directly in the random component, without using the mixin, but i need to open it with the mixin if it's possible.
Anyone have an idea of how to do it?
Related
I use vue js and I display a graph with chartjs. When I click on the graph I want emit an event for get data in parent component. My onClick function works but not the event.
Do you have an idea of my problem ?
Component Line2.vue
<script>
import { mixins, Line } from "vue-chartjs";
const { reactiveProp } = mixins;
export default {
extends: Line,
mixins: [reactiveProp],
props: ["options"],
mounted() {
const self = this;
console.log(self);
this.options.onClick = function (e, tooltipItems) {
console.log(tooltipItems[0].__ob__); //.logged
self.$emit("sendIndex", tooltipItems[0]._index);
};
this.renderChart(this.chartData, this.options);
},
};
</script>
<style scoped></style>
My main component
...
<h1 v-on:sendIndex="getIndexCoord($event)">{{ indexCoord }}</h1>
...
methods: {
getIndexCoord: function (e) {
console.log("rrr", e); //Not logged
this.indexCoord = e;
},
}
Regards
1.first you create EventBus.js file
import Vue from 'vue';
export const EventBus = new Vue();
2.In your char.js file code like below
import { EventBus } from "../EventBus.js";
import { mixins, Line } from "vue-chartjs";
const { reactiveProp } = mixins;
export default {
extends: Line,
mixins: [reactiveProp],
props: ["options"],
mounted() {
const self = this;
console.log(self);
this.options.onClick = function (e, tooltipItems) {
console.log(tooltipItems[0].__ob__); //.logged
EventBus.$emit("sendIndex", tooltipItems[0]._index);
};
this.renderChart(this.chartData, this.options);
},
};
where you want to access your data in that file like below
import { EventBus } from "../EventBus.js";
mounted() {
EventBus.$on('sendIndex', data => {
console.log(data)
});
},
Using vue-test-utils to test the component using pinia, I need to modify the value of the state stored in pinia, but I have tried many methods to no avail. The original component and store files are as follows.
// HelloWorld.vue
<template>
<h1>{{ title }}</h1>
</template>
<script>
import { useTestStore } from "#/stores/test";
import { mapState } from "pinia";
export default {
name: "HelloWorld",
computed: {
...mapState(useTestStore, ["title"]),
},
};
</script>
// #/stores/test.js
import { defineStore } from "pinia";
export const useTestStore = defineStore("test", {
state: () => {
return { title: "hhhhh" };
},
});
The following methods have been tried.
Import the store used within the component to the test code and make changes directly, but the changes cannot affect the component.
// test.spec.js
import { mount } from "#vue/test-utils";
import { createTestingPinia } from "#pinia/testing";
import HelloWorld from "#/components/HelloWorld.vue";
import { useTestStore } from "#/stores/test";
test("pinia in component test", () => {
const wrapper = mount(HelloWorld, {
global: {
plugins: [createTestingPinia()],
},
});
const store = useTestStore();
store.title = "xxxxx";
console.log(wrapper.text()) //"hhhhh";
});
Using the initialState in an attempt to overwrite the contents of the original store, but again without any effect.
// test.spec.js
import { mount } from "#vue/test-utils";
import { createTestingPinia } from "#pinia/testing";
import HelloWorld from "#/components/HelloWorld.vue";
test("pinia in component test", () => {
const wrapper = mount(HelloWorld, {
global: {
plugins: [createTestingPinia({ initialState: { title: "xxxxx" } })],
},
});
console.log(wrapper.text()) //"hhhhh";
});
Modify the TestingPinia object passed to global.plugins in the test code, but again has no effect.
// test.spec.js
import { mount } from "#vue/test-utils";
import { createTestingPinia } from "#pinia/testing";
import HelloWorld from "#/components/HelloWorld.vue";
test("pinia in component test", () => {
const pinia = createTestingPinia();
pinia.state.value.title = "xxxxx";
const wrapper = mount(HelloWorld, {
global: {
plugins: [pinia],
},
});
console.log(wrapper.text()) //"hhhhh";
});
Use global.mocks to mock the states used in the component, but this only works for the states passed in with setup() in the component, while the ones passed in with mapState() have no effect.
// test.spec.js
import { mount } from "#vue/test-utils";
import { createTestingPinia } from "#pinia/testing";
import HelloWorld from "#/components/HelloWorld.vue";
test("pinia in component test", () => {
const wrapper = mount(HelloWorld, {
global: {
plugins: [createTestingPinia()],
mocks: { title: "xxxxx" },
},
});
console.log(wrapper.text()) //"hhhhh"
});
This has been resolved using jest.mock().
import { mount } from "#vue/test-utils";
import { createPinia } from "pinia";
import HelloWorld from "#/components/HelloWorld.vue";
jest.mock("#/stores/test", () => {
const { defineStore } = require("pinia");
const useTestStore = defineStore("test", { state: () => ({ title: "xxxxx" }) });
return { useTestStore };
});
test("pinia in component test", () => {
const wrapper = mount(HelloWorld, {
global: { plugins: [createPinia()] },
});
expect(wrapper.text()).toBe("xxxxx");
});
Thanks to Red Panda for this topic. I use "testing-library", and "vue-testing-library" instead of "vue-test-utils" and "jest", but the problem is the same - couldn't change pinia initial data of the store.
I finally found a solution for this issue without mocking the function.
When you $patch data, you just need to await for it. Somehow it helps. My code looks like this and it totally works:
Popup.test.js
import { render, screen } from '#testing-library/vue'
import { createTestingPinia } from '#pinia/testing'
import { popup } from '#/store1/popup/index'
import Popup from '../../components/Popup/index.vue'
describe('Popup component', () => {
test('displays popup with group component', async () => {
render(Popup, {
global: { plugins: [createTestingPinia()] }
})
const store = popup()
await store.$patch({ popupData: 'new name' })
screen.debug()
})
})
OR you can set initialState using this scheme:
import { render, screen } from '#testing-library/vue'
import { createTestingPinia } from '#pinia/testing'
import { popup } from '#/store1/popup/index'
import Popup from '../../components/Popup/index.vue'
test('displays popup with no inner component', async () => {
const { getByTestId } = render(Popup, {
global: {
plugins: [
createTestingPinia({
initialState: {
popup: {
popupData: 'new name'
}
}
})
]
}
})
const store = popup()
screen.debug()
})
Where popup in initialState - is the imported pinia store from #/store1/popup. You can specify any of them there the same way.
Popup.vue
<script>
import { defineAsyncComponent, markRaw } from 'vue'
import { mapState, mapActions } from 'pinia'
import { popup } from '#/store1/popup/index'
export default {
data () {
return {}
},
computed: {
...mapState(popup, ['popupData'])
},
....
I'm working on a project using Vue 3 with composition API styling.
Composition API is used for both components and defining my store.
Here is my store
player.js
import { defineStore } from 'pinia'
import { ref, reactive } from 'vue'
export const usePlayerStore = defineStore('player',()=>{
const isMainBtnGameClicked = ref(false)
return { isMainBtnGameClicked }
})
MyComponent.vue
//import { usePlayerStore } from '...'
const playerStore = usePlayerStore()
playerStore.isMainBtnGameClicked = true
isMainBtnGameClicked from my store is updated properly.
You can also update variables from components by passing them by reference to the pinia store. It's working in my project.
For sake of saving future me many hours of trouble, there is a non-obvious thing in play here - the event loop. Vue reactivity relies on the event loop running to trigger the cascade of state changes.
When you mount/shallowMount/render a component with vue-test-utils, there is no event loop running automatically. You have to trigger it manually for the reactivity to fire, e.g.
await component.vm.$nextTick;
If you don't want to mess around with ticks, you have to mock the store state/getters/etc. (which the docs strongly lean toward, without explaining the necessity). Here OP mocked the whole store.
See also: Vue-test-utils: using $nextTick multiple times in a single test
I have been trying to figure this out for some time already, but I can not make it work! I found some examples on internet, but nothing solves it, every time I run my test I get:
Expected number of calls: 1
Received number of calls: 0
> 186 | expect(wrapper.vm.EventBus.$on).toHaveBeenCalledTimes(1);
The component looks like this:
import {EventBus} from 'eventbus'
export default{
data(){ return {}},
mounted(){
EventBus.$on('saveTerminal', function(){
this.someOtherFunction()
})
}
}
Event Bus file looks like this
import Vue from 'vue';
export const EventBus = new Vue();
The Test looks like this:
const GlobalPlugins = {
install(v) {
v.prototype.EventBus = new Vue();
},
};
//Vue.prototype.EventBus = new Vue(); <-- I tried this also, didn't do anything
// Mounting component
const $t = () => {}
const params = { localVue, store, router,
propsData: {
isEdit: false
},
data(){
return {
loading: false,
tabIndex: 1
};
},
mocks:{
$t,
EventBus: {
$on: jest.fn(),
$off: jest.fn(),
$emit: jest.fn()
}
},
}
const wrapper = shallowMount(MyComponent, params)
describe('My component', () => {
it('Event bus', () => {
wrapper.vm.EventBus.$emit('saveTerminal');
expect(wrapper.vm.EventBus.$on).toHaveBeenCalledTimes(1);
expect(wrapper.vm.EventBus.$on).toHaveBeenCalledWith('saveTerminal', expect.any(Function))
});
})
You can use jest.mock() to mock the EventBus module. Your test would require() the module to access the mock, and then verify its $on was called:
import { shallowMount } from '#vue/test-utils'
import MyComponent from '#/components/MyComponent.vue'
jest.mock('#/utils/EventBus')
describe('MyComponent.vue', () => {
it(`listens to 'saveTerminal' upon mounting`, async () => {
const { EventBus } = require('#/utils/EventBus')
shallowMount(MyComponent)
expect(EventBus.$on).toHaveBeenCalledWith('saveTerminal', expect.any(Function))
})
})
demo
I have the following file which is an external file with functions (language.js). I also have created a other component which needs to use language.js (it needs to use the languageText funcion inside language.js). I did used it in a Composition API component. But now I want to get it working in a Options API component. Please check the function inside methods called languageSelector. Inside this function I want to use the global function from language.js (languageText())
Any help?
Options API template (Form.vue)
<script>
import languageText from '#/composables/language';
export default defineComponent({
name: 'Form',
props: {
processingData: Object,
formData: Object
},
emits: ["gateway"],
components: {
Icon
},
data() {
return {
fieldData: this.formData,
}
},
methods: {
languageSelector(data) {
const h = languageText(data) **I want to USE the FUNCTION here.**
console.log(h)
return languageText(data)
},
}
language.js
import { ref, computed, watch } from 'vue';
import { useI18n } from "vue-i18n";
import { useStore } from "vuex";
export default function language() {
const store = useStore();
const i18n = useI18n();
const language = computed(() => {
return store.getters.currentUser.language;
});
function languageText(json) {
const obj = JSON.parse(json)
return obj[language.value]
}
return {
languageText
}
}
I would like to test if my getter is called in my component or view, but I don't understand how can it.
My method in the component :
computed: {
...mapGetters({ item: 'moduleA/getData' }),
},
And this is my unit test declaration :
beforeEach(() => {
store = new Vuex.Store({
modules: {
moduleA: {
state: {},
getters: {
getData() {
return { item: { name: 'test' } };
},
},
},
},
});
wrapper = shallowMount(MyComponent, {
store,
});
});
And I try to test if the data is loaded in my template:
it('should check if name is thruthy', () => {
expect(wrapper.find('.classA').text()).toEqual('test');
});
my component :
<template>
<v-content>
<ComponentA v-if="item.name"
key="keyA" ></ComponentA>
<ComponentB v-else key="keyA"></ComponentB>
</v-content>
</template>
<script>
import { mapGetters } from 'vuex';
import ComponentA from '#/components/ComponentA.vue';
import ComponentB from '#/components/ComponentB.vue';
export default {
/**
* Component's name :
*/
name: 'ViewA',
/**
* Component's used :
*/
components: {
ComponentA,
ComponentB,
},
/**
* computed's used :
*/
computed: {
...mapGetters({ item: 'moduleA/getData' }),
},
};
</script>
and my getter in the moduleA :
const getters = {
getData: state => state.data,
};
But I have this message:
TypeError: Cannot read property 'name' of undefined
Why? Thank you for your help.
As shown in docs, shallowMount's options has field named localVue. To solve your problem you should create a localVue, using createLocalVue and pass it to shallowMount.
createLocalVue returns a Vue class for you to add components, mixins
and install plugins without polluting the global Vue class.
import Vuex from 'vuex'
import { createLocalVue, shallowMount } from '#vue/test-utils'
beforeEach(() => {
const localVue = createLocalVue()
localVue.use(Vuex)
store = new Vuex.Store({
modules: {
moduleA: {
state: {},
getters: {
getData() {
return { item: { name: 'test' } }
},
},
},
},
})
wrapper = shallowMount(MyComponent, {
localVue,
store,
})
})