Jest + Coverage + VueJs how to cover vue methods? - vue.js

I was trying to cover the codes to increase the coverage
report percentage,
How to cover the if statement inside vue methods?
In my case using #vue/test-utils:"^1.1.4" and vue: "^2.6.12" package version, FYI, And below is my actual component,
<template>
<div :class="iconcls" >
<el-image
ref='cal-modal'
class="icons"
#click="handleRedirectRouter(urlname)"
:src="require(`#/assets/designsystem/home/${iconurl}`)"
fit="fill" />
<div class="desc" >{{ icondesc }}</div>
</div>
</template>
<script lang="ts">
import { Component, Vue, Prop } from 'vue-property-decorator';
#Component({
components: {}
})
class IconHolder extends Vue {
#Prop({ default: "" }) iconcls!: any;
#Prop({ default: "" }) iconurl!: any;
#Prop({ default: "" }) icondesc!: any;
#Prop({ default: "" }) urlname!: any;
handleRedirectRouter(url: string) {
if (url !== "") {
this.$router.push({ name: url });
}
}
}
export default IconHolder;
</script>
Coverage Report for Iconholder.vue component
EDIT 2 : Ater #tony updation,
i have tried with this below test suties but still getting errors,
import Vue from "vue";
import Vuex from "vuex";
import IconHolder from '#/components/designsystem/Home/IconHolder.vue';
import ElementUI, { Image } from "element-ui";
import { mount, createLocalVue } from '#vue/test-utils';
const localVue = createLocalVue();
localVue.use(Vuex);
localVue.use(ElementUI, {
Image
});
Vue.component('el-image', Image);
describe("IconHolder.spec.vue", () => {
it('pushes route by name', async () => {
const push = jest.fn();
const wrapper = mount(IconHolder, {
propsData: {
iconcls:"dshomesec5_comp_icons",
icondesc:"about",
iconurl:"components_icn_15.svg",
urlname: 'about'
},
mocks: {
$router: {
push
}
}
})
await wrapper.findComponent({ name: 'el-image' }).trigger('click');
expect(push).toHaveBeenCalledWith({ name: 'about' });
})
})
ERROR REPORT:
expect(jest.fn()).toHaveBeenCalledWith(...expected)
Expected: {"name": "about"}
Number of calls: 0
30 | })
31 | await wrapper.findComponent({ name: 'el-image' }).trigger('click');
> 32 | expect(push).toHaveBeenCalledWith({ name: 'about' })

Create a unit test that runs that method with a non-empty string for url.
Mount the component with an initial non-empty urlname prop.
Mock the $router.push method with jest.fn(), which we'll use to verify the call later.
Find the el-image component that is bound to that method (as a click handler).
Trigger the click event on that component.
Verify $router.push was called with the specified urlname.
it('pushes route by name', () => {
/* 2 */
const push = jest.fn()
const wrapper = shallowMount(IconHolder, {
/* 1 */
propsData: {
urlname: 'about'
},
/* 2 */
mocks: {
$router: {
push
}
}
})
/* 3 👇*/ /* 4 👇*/
await wrapper.findComponent({ name: 'el-image' }).trigger('click')
/* 5 */
expect(push).toHaveBeenCalledWith({ name: 'about' })
})

Related

Vuex + Jest + Composition API: How to check if an action has been called

I am working on a project built on Vue3 and composition API and writing test cases.
The component I want to test is like below.
Home.vue
<template>
<div>
<Child #onChangeValue="onChangeValue" />
</div>
</template>
<script lang="ts>
...
const onChangeValue = (value: string) => {
store.dispatch("changeValueAction", {
value: value,
});
};
</scirpt>
Now I want to test if changeValueAction has been called.
Home.spec.ts
...
import { key, store } from '#/store';
describe("Test Home component", () => {
const wrapper = mount(Home, {
global: {
plugins: [[store, key]],
},
});
it("Test onChangeValue", () => {
const child = wrapper.findComponent(Child);
child.vm.$emit("onChangeValue", "Hello, world");
// I want to check changeValueAction has been called.
expect(wrapper.vm.store.state.moduleA.value).toBe("Hello, world");
});
});
I can confirm the state has actually been updated successfully in the test case above but I am wondering how I can mock action and check if it has been called.
How can I do it?
I have sort of a similar setup.
I don't want to test the actual store just that the method within the component is calling dispatch with a certain value.
This is what I've done.
favorite.spec.ts
import {key} from '#/store';
let storeMock: any;
beforeEach(async () => {
storeMock = createStore({});
});
test(`Should remove favorite`, async () => {
const wrapper = mount(Component, {
propsData: {
item: mockItemObj
},
global: {
plugins: [[storeMock, key]],
}
});
const spyDispatch = jest.spyOn(storeMock, 'dispatch').mockImplementation();
await wrapper.find('.remove-favorite-item').trigger('click');
expect(spyDispatch).toHaveBeenCalledTimes(1);
expect(spyDispatch).toHaveBeenCalledWith("favoritesState/deleteFavorite", favoriteId);
});
This is the Component method:
setup(props) {
const store = useStore();
function removeFavorite() {
store.dispatch("favoritesState/deleteFavorite", favoriteId);
}
return {
removeFavorite
}
}
Hope this will help you further :)

Vue3 reactive components on globalProperties

In vuejs 2 it's possible to assign components to global variables on the main app instance like this...
const app = new Vue({});
Vue.use({
install(Vue) {
Vue.prototype.$counter = new Vue({
data: () => ({ value: 1 }),
methods: {
increment() { this.value++ },
}
});
}
})
app.$mount('#app');
But when I convert that to vue3 I can't access any of the properties or methods...
const app = Vue.createApp({});
app.use({
install(app) {
app.config.globalProperties.$counter = Vue.createApp({
data: () => ({ value: 1 }),
methods: {
increment() { this.value++ }
}
});
}
})
app.mount('#app');
Here is an example for vue2... https://jsfiddle.net/Lg49anzh/
And here is the vue3 version... https://jsfiddle.net/Lathvj29/
So I'm wondering if and how this is still possible in vue3 or do i need to refactor all my plugins?
I tried to keep the example as simple as possible to illustrate the problem but if you need more information just let me know.
Vue.createApp() creates an application instance, which is separate from the root component of the application.
A quick fix is to mount the application instance to get the root component:
import { createApp } from 'vue';
app.config.globalProperties.$counter = createApp({
data: () => ({ value: 1 }),
methods: {
increment() { this.value++ }
}
}).mount(document.createElement('div')); 👈
demo 1
However, a more idiomatic and simpler solution is to use a ref:
import { ref } from 'vue';
const counter = ref(1);
app.config.globalProperties.$counter = {
value: counter,
increment() { counter.value++ }
};
demo 2
Not an exact answer to the question but related. Here is a simple way of sharing global vars between components.
In my main app file I added the variable $navigationProps to global scrope:
let app=createApp(App)
app.config.globalProperties.$navigationProps = {mobileMenuClosed: false, closeIconHidden:false };
app.use(router)
app.mount('#app')
Then in any component where I needed that $navigationProps to work with 2 way binding:
<script>
import { defineComponent, getCurrentInstance } from "vue";
export default defineComponent({
data: () => ({
navigationProps:
getCurrentInstance().appContext.config.globalProperties.$navigationProps,
}),
methods: {
toggleMobileMenu(event) {
this.navigationProps.mobileMenuClosed =
!this.navigationProps.mobileMenuClosed;
},
hideMobileMenu(event) {
this.navigationProps.mobileMenuClosed = true;
},
},
Worked like a charm for me.
The above technique worked for me to make global components (with only one instance in the root component). For example, components like Loaders or Alerts are good examples.
Loader.vue
...
mounted() {
const currentInstance = getCurrentInstance();
if (currentInstance) {
currentInstance.appContext.config.globalProperties.$loader = this;
}
},
...
AlertMessage.vue
...
mounted() {
const currentInstance = getCurrentInstance();
if (currentInstance) {
currentInstance.appContext.config.globalProperties.$alert = this;
}
},
...
So, in the root component of your app, you have to instance your global components, as shown:
App.vue
<template>
<v-app id="allPageView">
<router-view name="allPageView" v-slot="{Component}">
<transition :name="$router.currentRoute.name">
<component :is="Component"/>
</transition>
</router-view>
<alert-message/> //here
<loader/> //here
</v-app>
</template>
<script lang="ts">
import AlertMessage from './components/Utilities/Alerts/AlertMessage.vue';
import Loader from './components/Utilities/Loaders/Loader.vue';
export default {
name: 'App',
components: { AlertMessage, Loader }
};
</script>
Finally, in this way you can your component in whatever other components, for example:
Login.vue
...
async login() {
if (await this.isFormValid(this.$refs.loginObserver as FormContext)) {
this.$loader.activate('Logging in. . .');
Meteor.loginWithPassword(this.user.userOrEmail, this.user.password, (err: Meteor.Error | any) => {
this.$loader.deactivate();
if (err) {
console.error('Error in login: ', err);
if (err.error === '403') {
this.$alert.showAlertFull('mdi-close-circle', 'warning', err.reason,
'', 5000, 'center', 'bottom');
} else {
this.$alert.showAlertFull('mdi-close-circle', 'error', 'Incorrect credentials');
}
this.authError(err.error);
this.error = true;
} else {
this.successLogin();
}
});
...
In this way, you can avoid importing those components in every component.

QUASAR: Redirection using "push" does not work

Good day. I have the following file "pages / Login.vue"
Here the form:
Simple form
<template>
<div>
<q-form #submit="btnlogin">
<q-input v-model="user" type="text" label="Usuario" />
<q-input v-model="pass" type="password" label="Contraseña" />
<q-btn color="primary" label="Ingresar" type="submit"/>
</div>
</template>
<script>
import axios from 'axios'
import { ref } from 'vue'
import { useQuasar } from 'quasar'
import router from 'src/router/index'
export default {
setup () {
const $q = useQuasar()
const user = ref(null)
const pass = ref(null)
const btnlogin = async () => {
axios.post("http://localhost:3050/loginQuest",{
uss : user.value,
pww : pass.value
})
.then(resp=>{
if(resp.data=="ERROR"){
$q.notify({
type:'negative',
message:'Datos incorrectos!'
})
}
else{
router().push({ path: '/' })
}
})
}
return {
user, pass, btnlogin
}
}
}
</script>
When the verification is successful, the address bar changes to http://localhost: 8080 but the content does not change and the Login.vue form continues to be displayed on the screen.
it sends me to the path but does not change the content, but if I refresh the page it shows the correct content
This is my router/routes.js:
const routes = [
{
path: '/',
component: () => import('layouts/MainLayout.vue'),
children: [
{ path: '', component: () => import('pages/Index.vue') },
{ path: '/form', component: () => import('pages/Form.vue') },
{ path: '/user', component: () => import('pages/Usuarios.vue') },
{ path: '/prueba', component: () => import('pages/Prueba.vue') },
{ path: '/facturas', component: () => import('pages/Facturas.vue') },
],
},
{ path: '/login', component:()=> import('pages/Login.vue')},
{ path: '/:catchAll(.*)*', component: () => import('pages/Error404.vue')}
]
export default routes
I changed the quasar.conf.js setting in the "vueRouterMode" section from hash to history. I hope you can help me, I'm stuck in it. Thank you!
Your script should look something like this:
<script>
import axios from 'axios'
import { ref } from 'vue'
import { useQuasar } from 'quasar'
import { useRoute } from 'vue-router' // <- import useRoute here
export default {
setup () {
const $q = useQuasar()
const router = useRouter()
const user = ref(null)
const pass = ref(null)
const btnlogin = async () => {
axios.post("http://localhost:3050/loginQuest",{
uss : user.value,
pww : pass.value
})
.then(resp=>{
if(resp.data=="ERROR"){
$q.notify({
type:'negative',
message:'Datos incorrectos!'
})
}
else{
router.push({ path: '/' }) // << router is an object, not a function
}
})
}
return {
user, pass, btnlogin
}
}
}
</script>
Is Posible that on you are created route on yout router.js or router/index.js a method for wraper router (if you show you router definition help to know it).
but I was a similar problem, I resolve it with:
let router: Router;
...
export default route(function ( ... ) {
if (router) {
return router;
}
....
router = createRouter({
... // your code
});
return router;
});
it require unique intanciated object router. It solve for me.

Vue Test Utils - Unable to correctly mount/shallow mount component, wrapper undefined

I've tried almost everything I can think of but I'm unable to correctly mount/shallow mount my vue components for testing correctly. Everytime I console.log the wrapper I get the following print out:
VueWrapper {
isFunctionalComponent: undefined,
_emitted: [Object: null prototype] {},
_emittedByOrder: []
}
This question is similar to this question asked here:
Vue-test-utils wrapper undefined
I'm using Vuetify, Vuex and Vue Router. My test.spec.ts is below:
import { shallowMount, createLocalVue, mount } from "#vue/test-utils"
import Vuex from "vuex"
import Vuetify from "vuetify"
import VueRouter from "vue-router"
import TheExamAnswer from "#/components/common/TheExamAnswer.vue"
describe("TheExamAnswer.vue", () => {
const localVue = createLocalVue()
let getters: any
let store: any
let vuetify: any
let router: any
beforeEach(() => {
localVue.use(Vuex)
localVue.use(Vuetify)
localVue.use(VueRouter)
getters = {
getExam: () => true,
}
store = new Vuex.Store({
modules: {
// Need to add FlightPlanning for name spacing
FlightPlanning: {
namespaced: true,
getters,
},
},
})
vuetify = new Vuetify()
router = new VueRouter()
})
it("Renders the element if the exam has been submitted", () => {
const wrapper = mount(TheExamAnswer, { localVue, store, router })
console.log("This is the HTML", wrapper.html())
expect(wrapper.text()).toContain("Show Answer")
})
})
My view component is very simple and the code is below:
<template>
<div v-if="submitted" class="div">
<v-btn #click="answerHidden = !answerHidden" class="mb-10"
>Show Answer</v-btn
>
<div v-if="!answerHidden">
<slot name="questionAnswer"></slot>
</div>
</div>
</template>
<script>
export default {
data: () => {
return {
answerHidden: true,
}
},
computed: {
submitted() {
const exam = this.$store.getters["FlightPlanning/getExam"]
return exam.submitted
},
},
}
</script>
<style></style>
UPDATED: I've added the suggestion from the answer below however now I"m getting the following message.
TheExamAnswer.vue
✕ Renders the element if the exam has been submitted (49ms)
● TheExamAnswer.vue › Renders the element if the exam has been submitted
expect(received).toContain(expected) // indexOf
Expected substring: "Show Answer"
Received string: ""
38 | const wrapper = mount(TheExamAnswer, { localVue, store, router })
39 | console.log("This is the HTML", wrapper.html())
> 40 | expect(wrapper.text()).toContain("Show Answer")
| ^
41 | })
42 | })
43 |
at Object.it (tests/unit/test.spec.ts:40:28)
console.error node_modules/vuetify/dist/vuetify.js:43612
[Vuetify] Multiple instances of Vue detected
See https://github.com/vuetifyjs/vuetify/issues/4068
If you're seeing "$attrs is readonly", it's caused by this
console.log tests/unit/test.spec.ts:39
This is the HTML
Test Suites: 1 failed, 1 total
Tests: 1 failed, 1 total
As you can see the HTML is blank and therefore I'm presuming that's also the same reason it's failing this test as the received string is "".
SOLUTION -
I figured it out. The error was on my behalf by not looking at the logic of the computed property correctly.
In my test I had:
getters = {
getExam: () => true,
}
In my component I had:
computed: {
submitted() {
const exam = this.$store.getters["FlightPlanning/getExam"]
return exam.submitted
},
If you look at the logic of the computed property it going to take whats returned from the getter and assign it to the exam variable. Originally I was returning true, because that's what I wanted the submitted() function to return this means when I call exam.submitted I'm calling it on a boolean value which obviously gives me "undefined". The solution was to return exactly what the computed property was designed to deal with, an object i.e. {submitted:true}
Therefore the final test looks like this and is returning valid HTML.
import { shallowMount, createLocalVue, mount } from "#vue/test-utils"
import Vuex from "vuex"
import Vuetify from "vuetify"
import VueRouter from "vue-router"
import TheExamAnswer from "#/components/common/TheExamAnswer.vue"
const localVue = createLocalVue()
localVue.use(Vuex)
localVue.use(Vuetify)
localVue.use(VueRouter)
describe("test.vue", () => {
let getters: any
let store: any
let vuetify: any
let router: any
beforeEach(() => {
getters = {
getExam: () => {
return { submitted: true }
},
}
store = new Vuex.Store({
modules: {
// Need to add FlightPlanning for name spacing
FlightPlanning: {
namespaced: true,
getters,
},
},
})
vuetify = new Vuetify()
router = new VueRouter()
})
it("Renders the element if the exam has been submitted", () => {
const wrapper = mount(TheExamAnswer, { localVue, vuetify, store, router })
console.log("This is the HTML", wrapper.html())
})
})
This gives me the result of:
console.log tests/unit/test.spec.ts:44
This is the HTML <div><button type="button" class="mb-10 v-btn v-btn--contained theme--light v-size--default"><span class="v-btn__content">Show Answer</span></button>
<!---->
</div>
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 5.235s
Ran all test suites.
The console.log with that weird input for wrapper or elements is normal behaviour. I ran couple tests with your components and everything was working.
it("Renders the element if the exam has been submitted", () => {
const wrapper = mount(TheExamAnswer, { localVue, store, router });
expect(wrapper.text()).toContain("Show Answer");
});
If you want to console.log html in your wrapper:
console.log(wrapper.html())
UPDATED: the reason, why wrapper.html() return empty string is v-if="submitted" on your root component. The computed property return undefined, because getter return true, so true.submitted return undefined
Getter in test.spec.ts:
getters = {
getExam: () => {
return { submitted: true };
}
};

Component clean up fails between tests with Vue test-utils

I have a simple component (HelloComponent) and a couple of tests. First test shallow mounts the component, prints it (wrapper of the component) on the console, and finally calls destroy() api on it. And the second test just prints it without mounting it. I was expecting the second test to print undefined but it prints the same thing (full component markup) as first test. Is my expectation incorrect ?
<!-- HelloComponent.vue -->
<template>
<div>
Hello {{name}}!
</div>
</template>
<script lang="ts">
export default {
name: 'Hello',
data() {
return {
name: ''
};
},
methods: {
setName(name) {
this.name = name;
}
}
}
</script>
import { shallowMount } from '#vue/test-utils';
import HelloComponent from '#/HelloComponent.vue';
describe('Hello component unit tests', () => {
let wrapper;
describe('Set 1', () => {
it('should load component', () => {
wrapper = shallowMount(HelloComponent, {});
expect(wrapper.exists()).toBe(true);
wrapper.vm.setName('oomer');
console.log(wrapper.html());
wrapper.destroy();
});
});
describe('Set 2', () => {
it('should log empty component', () => {
expect(wrapper.vm.name).toEqual('oomer');
console.log(wrapper.html());
});
});
});