How to mock extended component vue.js - javascript

I have the following problem, I want to test a component in vuejs which extends another component like this :
<template>
<div></div>
</template>
<script>
import MySuperComponent from '#/project/MySuperComponent'
export default {
extends: MySuperComponent,
name: myComponent,
components: {
}
</script>
my test look like this :
import {createLocalVue, shallowMount, mount} from '#vue/test-utils'
// Component to test
import myComponent from '#/project/myComponent.vue'
// import store
import Vuex from 'vuex'
// LIB
import VueI18n from "vue-i18n"
describe(`myComponent.vue`, () => {
const localVue = createLocalVue()
let i18n, store, getters, state, mutations, actions
beforeAll(() => {
localVue.use(Vuex)
getters = {
mygetters: jest.fn()
}
state = {
getNames: jest.fn(),
}
mutations = {}
actions = {}
store = new Vuex.Store({
getters, state, mutations, actions
})
localVue.use(VueI18n)
i18n = new VueI18n({
silentTranslationWarn: true
})
})
it(`Test default mounted myComponent ok`, () => {
const wrapper = mount(myComponent, {
propsData: {
component : 'mycompnent',
json : {},
animationEnabled: true
},
computed: {
getNames : jest.fn(),
},
watch: {
ageUser : jest.fn(),
},
i18n,
localVue,
store
})
expect(wrapper.exists()).toBeTruthy()
})
})
the problem is even if my component is empty I need to set all the props of the extended component and all the computed .... I tried using jest.mock(MySuperComponent) but nothing work, my goal here is just to test what's inside my component

Related

Testing Vuejs EventBus

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

vuex unknown action type: showRegisterLogin/show

I wrote the following code but it shows an error. What is the reason for this?
Error
[vuex] unknown action type: showRegisterLogin/show
HomePage.vue // component
When using the sh method This error is caused
import { mapState, mapActions } from "vuex";
export default {
name: "HomePage",
components: {
RegisterLogin
},
data() {
return {}
},
computed: {
...mapState({
showRegisterLogin: state => state.showRegisterLogin.show
}),
},
methods: {
sh() {
this.$store.dispatch('showRegisterLogin/show');
}
}
}
/ store / modules / showRegisterLogin.js
// States
const state = {
show: false,
};
// Getters
const getter = {
show (state) {
return state.show;
}
};
// Mutations
const mutation = {
showPage (state) {
return state.show = true;
},
hidePage (state) {
return state.show = false;
}
};
// Actions
const action = {
show({ commit }) {
commit('showPage');
},
hide({ commit }) {
commit('hidePage');
}
};
export default {
namespaced: true,
state,
getter,
mutation,
action
}
/ store / store.js
'use strict';
import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);
import showRegisterLogin from "./modules/showRegisterLogin";
export default new Vuex.Store({
modules: {
showRegisterLogin,
}
});
I also imported the store.js file into app.js and registered it in new vue
The structure of the store, module, and component are fine, except for the name of the store objects in your module:
getter should be getters
mutation should be mutations
action should be actions
Probably just typos. Those can't be arbitrarily named since Vuex looks specifically for those keys.

Testing a NUXT.js and Vue.js app with Jest. Getting '[vuex] module namespace not found in mapState()' and '[vuex] unknown action type'

In spite of my understanding that NUXT does namespacing automatically. Because of this, I am unable to test or reference the store in any of my testing modules. Can anyone give me a tip? Maybe where I can edit the namespacing property in a Nuxt app?
Here is the code below for the component, store, and the test.
ButtonComponent.vue:
<template>
<v-container>
<v-btn #buttonClick v-model="value"></v-btn>
</v-container>
</template>
<script>
import { mapState, mapActions } from 'vuex'
export default {
data: {
return {
value: 25
}
}
methods: {
buttonClick(event) {
this.$store.dispatch('buttonComponent/setNewValue', valuePassedIn)
},
},
}
</script>
<style scoped></style>
buttonComponent.spec.js:
import Component from '../../Component'
import { mount, createLocalVue } from '#vue/test-utils'
import expect from 'expect'
import Vue from 'vue'
import Vuex from 'vuex'
import Vuetify from 'vuetify'
const localVue = createLocalVue()
localVue.use(Vuex)
Vue.use(Vuetify)
describe('Component', () => {
let store
let vuetify
let actions
beforeEach(() => {
actions = {
actionClick: jest.fn()
}
store = new Vuex.Store({
actions,
})
vuetify = new Vuetify()
})
it('method sends value to store when button is clicked', async () => {
const wrapper = mount(Component, {
store,
localVue,
vuetify,
})
wrapper.find('.v-btn').trigger('click')
expect(actions.actionClick).toHaveBeenCalledWith('buttonComponent/setNewValue', 25)
})
})
buttonComponent.js:
export const state = () => ({
value: 0,
})
export const mutations = {
SET_TO_NEW_VALUE(state, value) {
state.value = value
},
}
export const actions = {
setNewValue({ commit }, value) {
commit('SET_TO_NEW_VALUE', value)
},
}
Just so that I don't have to write it again here, I'll link you to an article I just posted that walks through the setup process to so you can test your Nuxt stores with Jest: https://medium.com/#brandonaaskov/how-to-test-nuxt-stores-with-jest-9a5d55d54b28

How Test MapGetter

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,
})
})

How to mock vue router in a Vuex store test with Jest?

I have a vuex store like this:
// store.js
import Vuex from 'vuex'
import router from '../router' // this is a vuejs router
export const actions = {
async load({ dispatch, commit }) {
if (router.currentRoute.name === 'one-route') {
dispatch('oneModule/oneAction', null, { root: true })
}
}
}
export default new Vuex.Store({
state,
actions,
...
})
I would like to test it with Jest.
// store.test.js
import { createLocalVue } from '#vue/test-utils'
import Vuex from 'vuex'
import VueRouter from 'vue-router'
import { actions } from './store'
const localVue = createLocalVue()
localVue.use(Vuex)
localVue.use(VueRouter)
describe('store tests', () => {
let store, router, oneAction
beforeEach(() => {
oneAction = jest.fn()
const modules = {
oneModule: {
namespaced: true,
actions: { oneAction }
}
}
store = new Vuex.Store({ actions, modules })
router = new VueRouter({ routes: [{ name: 'one-route' }] })
}
test('call module action if one-route is selected', async () => {
router.push({ name: 'one-route' })
await store.dispatch('load')
expect(oneAction).toHaveBeenCalled()
})
}
This makes the following error:
Expected mock function to have been called, but it was not called.
What is the correct way to mock the router to make this test pass?
Thank you

Categories

Resources