My current setup involves using vue-test-utils along with jest for Test-Driven Development (TDD). In the route file (routes.js) of my Vue.js application, I have imported the $store object and utilized it for various functionalities. While writing a basic unit test for the login page, I encountered an error even before any tests could be executed.
Error:
TypeError: Cannot read property 'state' of undefined
130 | isAuth: true,
> 131 | layout: $store.state.dom.isMobile ? mobileSinglePage : panel
| ^
route.js:
import $store from "../store"
// --------- layouts
import panel from "../layout/panel";
import mobileSinglePage from "../layout/mobileSinglePage";
import MainLayout from "../layout/index";
import auth from "../layout/auth"
// transactions
import _transaction from "../pages/transaction/_transaction"
const routes = [
{
path: "",
component: MainLayout,
children: [
{
path: "",
redirect: "/panel/dashboard",
},
{
path: "login",
component: login,
name: "login",
meta: {
preventLoggedIn: true,
layout: auth
}
},
{
path: "/panel/transactions/:url",
name: "_transactions",
component: _transaction,
meta: {
isAuth: true,
layout: $store.state.dom.isMobile ? mobileSinglePage : panel
}
},
{
path: "*",
name: 'error_page',
redirect: '/404'
}
],
},
];
export default routes;
login.spec.js
import { mount, createLocalVue } from "@vue/test-utils"
import login from '@/pages/auth/login'
import Vuex from "vuex"
const localVue = createLocalVue()
localVue.use(Vuex)
describe("login", () => {
it("simple test", () => {
const wrapper = mount(login, {
localVue,
data(){
return {
form: {
mobile_number: '',
},
}
},
})
wrapper.find('#login').text()
})
})
Login.vue
<template>
<div class="w-100">
<transition>
<form @submit.prevent="requestOtp" class="w-100" v-if="step === 1">
<MobileInput
ref="mobile_number"
v-model="form.mobile_number"
autocomplete="false"
outlined
:counter="false"
label="mobile number"
/>
<AppButton
:disabled="!form.mobile_number || form.mobile_number.length !== 11"
type="submit"
color="secondary"
large
:loading="loading"
class="w-100 fontMobileMedium font0.875 loginBtn">
login
</AppButton>
</form>
</transition>
<transition>
<form @submit.prevent="verifyOtp" v-if="step === 2">
<AppPinCode
autofocus
dir="ltr"
:disabled="loading"
:length="6"
class="mb-6"
@complete="verifyOtp"
v-model="form.otpCode"/>
<AppButton
type="submit"
:loading="loading"
:disabled="!form.otpCode"
color="secondary"
large
class="w-100 fontMobileMedium font0.875 ">
login
</AppButton>
</form>
</transition>
</div>
</template>
<script>
// Import statements and code for Login.vue...
</script>
store/dom.js(store module)
// Code for store dom.js...
store/index.js
// Code for store index.js...
It seems that the error related to the router object is being thrown in the test file without explicitly using it. This issue needs further investigation.