Jest : How to mock vue-router used in vuex - vue.js

I tried to use vue-router inside actions of vuex, which is working fine at localhost.
However, i got errors when I tried to prepare store(for mock) by importing "actions" from store file.
Could you help me out in this issue?
versions
vue-test-utils: 1.0.0-beta.16
yarn: 1.5.1
vuejs: 2.5.13
vue-jest: 1.4.0
error msg
FAIL test/components/main.test.js
● Test suite failed to run
/Users/gulliver/Desktop/test/vue-test-utils-jest-example/node_modules/vue/dist/vue.esm.js:10809
export default Vue$3;
^^^^^^
SyntaxError: Unexpected token export
at ScriptTransformer._transformAndBuildScript (node_modules/jest-runtime/build/script_transformer.js:305:17)
at Object.<anonymous> (src/router/main.js:1:203)
at Object.<anonymous> (src/store/main.js:3:13)
Test Suites: 1 failed, 1 total
Tests: 0 total
Snapshots: 0 total
Time: 2.354s
Ran all test suites matching /test\/components\/main.test.js/i.
error An unexpected error occurred: "Command failed.
Exit code: 1
app/src/main.js
import Vue from "vue/dist/vue.esm";
import App from './App.vue'
import store from './store/main.js';
import router from './router/main.js';
new Vue({
el: '#app',
render: h => h(App),
store,
router,
})
app/src/store/main.js
import Vue from "vue";
import Vuex from 'vuex';
import router from '../router/main.js'
Vue.use(Vuex)
export const actions = {
locationTo(context, url){
router.push(url)
}
}
export default new Vuex.Store({
actions,
})
app/src/router/main.js
import Vue from "vue/dist/vue.esm";
import VueRouter from 'vue-router';
import root from '../components/root.vue';
import hoge from '../components/hoge.vue';
Vue.use(VueRouter)
export const routes = [
{ path: '/', component: root},
{ path: '/hoge', component: hoge},
];
export default new VueRouter({
mode: 'history',
routes
})
app/test/components/main.test.js
import Vue from "vue";
import Vuex from "vuex";
import { shallowMount, createLocalVue } from "#vue/test-utils";
import { actions } from "#/store/main"; //NOTE: this causes error
import _ from "lodash";
const localVue = createLocalVue();
import root from '#/components/root.vue'
import hoge from '#/components/hoge.vue'
describe('increment.vue', () => {
let propsData;
let store;
let wrapper;
beforeEach(() => {
propsData = _.cloneDeep(personObject)
store = new Vuex.Store(_.cloneDeep({
actions,
}))
const $route = {
path: '/hoge', components: hoge
}
wrapper = shallowMount(root, {
localVue,
propsData,
store,
use: ['Vuex'],
stubs: ['router-view'],
mocks: {
$route
}
})
});
it('test:router in store', () => {
// check if URL changed after action executed
});
})
components
// App.vue
<template>
<div id="app">
<router-view></router-view>
</div>
</template>
// root.vue
<template>
<div>
<p>root component</p>
</div>
</template>
<script>
export default {
mounted () {
this.$store.dispatch('locationTo', '/hoge')
},
}
</script>
// hoge.vue
<template>
<div>
<p>hoge template</p>
</div>
</template>

This error is related to the fact that Jest runs in a Node.js environment, and you are using export default, which does not work by default in Node.js (Node uses module.exports). I guess you are using webpack for your dev/production build, but not for the test environment.
Are you using Jest? If so, you will need to set up babel-jest so Jest knows how to read ES Modules syntax (import/export).
Read more here: https://vue-test-utils.vuejs.org/guides/#testing-single-file-components-with-jest
This can be annoying to set up, let me know if you need more help to get it working.

Related

Why do I see a previous route component when using vue router 3 navigation?

Let's say we have 3 routes and for the sake of making it simple, they're just referred to as 1, 2, and 3.
When I navigate to route 1 -> route 2 -> route 3 -> route 1, route 2 shows between the navigation from route 3 -> route 1. I can't for the life of me figure out why that's happening.
Routes file is like:
import Vue from 'vue';
import VueRouter from 'vue-router';
import Route1 from '../views/Route1';
import Route2 from '../views/Route2';
import Route3 from '../views/Route3';
Vue.use(VueRouter);
const routes = [
{
path: '/route1',
name: 'Route1',
component: Route1
},
{
path: '/route2',
name: 'Route2',
component: Route2
},
{
path: '/route3',
name: 'Route3',
component: Route3
}
];
const router = new VueRouter({
mode: 'history',
base: '/',
query: {
t: window.token
},
routes
});
export default router;
main.js
import 'sass/main.scss';
import moment from 'moment';
import Vue from 'vue';
import { mapActions, mapState } from 'vuex';
import App from './App.vue';
import api from './plugins/api.js';
import vuetify from './plugins/vuetify';
import router from './router';
import store from './store';
Vue.prototype.$moment = moment;
Vue.use(api);
Vue.config.productionTip = false;
new Vue({
computed: {
...mapState
},
methods: {
...mapActions
},
router,
store,
vuetify,
watch: {
$route() {
try {
// ... some action(s) on route change - removed here
} catch (error) {
// ... error handling removed
}
}
},
render: h => h(App)
}).$mount('#app');
App.vue
<template>
<v-app>
<!-- header/app bar removed here -->
<v-main>
<v-progress-linear
v-if="loading"
color="primary lighten-2"
height="2"
indeterminate
/>
<router-view v-else />
</v-main>
<!-- footer removed here -->
</v-app>
</template>
Kind of dumb, but I'll put it out there anyway. My components were rendering dynamic components that were in the store... upon navigating to a new route I just had to clear the stored component array while the new component array was fetched from the API. So when going back to another route it was first seeing a flash of the old array of dynamic componets.

How can I set up moment.js in the vuetify?

I using vuetify : https://vuetifyjs.com/en/
I want to use moment.js. So I read this reference : https://www.npmjs.com/package/vue-moment
I had run npm install vue-moment
I'm still confused to put this script Vue.use(require('vue-moment'));
In the vuetify, there exist two file : main.js and index.js
main.js like this :
import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store/index'
import './registerServiceWorker'
import vuetify from './plugins/vuetify'
Vue.config.productionTip = false
new Vue({
router,
store,
vuetify,
render: h => h(App)
}).$mount('#app')
index.js like this :
import Vue from 'vue';
import Vuex from 'vuex';
import dataStore from './modules/data-store';
import createLogger from "vuex/dist/logger";
Vue.use(Vuex);
const debug = process.env.VUE_APP_DEBUG !== "production";
export default new Vuex.Store({
modules: {
dataStore
},
strict: debug,
plugins: debug ? [createLogger()] : []
});
where do i put Vue.use(require('vue-moment'));?
I try to put it in the main.js, but if i call my vue component, there exist error : ReferenceError: moment is not defined
My vue component like this :
<template>
...
</template>
<script>
export default {
mounted() {
let a = moment("2012-02", "YYYY-MM").daysInMonth();
console.log(a)
}
};
</script>
I found this at the bottom of the vue-moment npm page
vue-moment attaches the momentjs instance to your Vue app as
this.$moment.
This allows you to call the static methods momentjs provides.
So you should be able to use your original configuration of vue-moment and do this in your mounted() method
mounted() {
let a = this.$moment("2012-02", "YYYY-MM").daysInMonth();
console.log(a)
}
notice this.$moment
And for the set up of vue-moment you should place this in your main.js file
main.js
Vue.use(require('vue-moment'))
=========================================================================
GLOBAL
If you want to use moment with Vue globally you can create an Instance Proprety
main.js
import moment from 'moment'
Vue.prototype.moment = moment
In your component you then call this.moment in your methods or computed properties. In your mounted section it would look like this
mounted() {
let a = this.moment("2012-02", "YYYY-MM").daysInMonth();
console.log(a)
}
COMPONENT
If you just want to use moment in a component you can include directly like this
<script>
import moment from 'moment'
export default {
mounted(){
let a = moment("2012-02", "YYYY-MM").daysInMonth();
console.log(a)
}
}
</script>

Load store into vue js

while I am trying to load page it's showing me error "TypeError: Cannot read property 'state' of undefined". As per documentation I have tried this bus not loading store.
<template>
<div>
</div>
</template>
<script>
import { store } from '#/components/tenant/store/store'
import Vue from 'vue'
export default {
store:store,
data: () => {
return {
}
}
}
store.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export const userStore = new Vuex.Store({
state: {}
})
Maybe I have misunderstood your question, but since you're exporting the const userStore, don't you need to do the following:
import { userStore } from '#/components/tenant/store/store';

I can't access to Vuex data: using vue-cli webpack

Right now, I'm trying to show the contents of state object from store.js on my App.vue.
I've tried vuex examples on Medium and other website, but I'm keep failing: non of them worked: some of them even gave me a WebPack config error.
My App.vue
<template>
<div id="app">
<img src="./assets/logo.png">
<h1>TEST</h1>
</div>
</template>
<script>
import Store from './store/index'
export default {
name: 'App',
Store
}
</script>
My store/index.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
alpha: ['1st data']
},
mutations: {
ADD ({ alpha }) {
const beta = 'new!'
state.alpha.push(beta)
}
}
})
My main.js
import Vue from 'vue'
import App from './App'
import Vuex from 'vuex'
import store from './store/index'
Vue.config.productionTip = false
/* eslint-disable no-new */
new Vue({
el: '#app',
store,
components: { App },
template: '<App/>'
})
You shouldn't be importing the store in App.vue. It only needs to be included in main.js and passed as an option when constructing the Vue instance. Within a component, the store is thereafter accessible via this.$store.
Second, your mutation should receive a context object as it's first parameter. context consists of properties such including state and commit. Those are the ways in which you access state within a mutation.
// notice context is the first parameter
mutations: {
ADD (context, { param }) {
const beta = 'new!'
context.state.alpha.push(beta)
})
}
// you can also deconstruct context like this
mutations: {
ADD ({state}, { param }) {
const beta = 'new!'
state.alpha.push(beta)
})
}
I also changed the way alpha to param. You don't receive the state's properties unless you destructure even further.
The problem is that in your main.js is missing Vue.use(veux)
you should have something like this:
import Vue from 'vue'
import Vuex from 'vuex'
import App from './App'
import store from './store'
Vue.use(Vuex) // <-- Add this
/* eslint-disable no-new */
new Vue({
el: '#app',
store,
template: '<App/>',
components: { App }
})

vue 2.0 and vue-router 2.0 build SPA, router-view did not update

Build A Single page app with vue 2 and vue-router 2 and vuex 2, but do not update
/src/main.js
import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
import { sync } from 'vuex-router-sync'
sync(store, router)
new Vue({
router,
store,
...App
}).$mount('#app')
/src/router/index.js
import Vue from 'vue'
import routes from './routes'
import VueRouter from 'vue-router'
Vue.use(VueRouter)
const router = new VueRouter({
mode: 'history',
routes
})
export default router
/src/router/routes.js
import loader from './loader'
const routes = [
{ path: '/index', name: 'index', component: (r) => require(['./../views/index.vue'], r) }
]
export default routes
/src/store/index.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const store = new Vuex.Store({
modules: {}
})
export default store
/src/view/index.vue
<template>
<div>
<h1>Hello index</h1>
</div>
</template>
<script>
import loader from './../../../router/loader'
export default {
name: 'index',
created () {
console.log('This is index')
}
}
</script>
/src/App.vue
<template>
<div id="app">
<router-link :to="'index'">index</router-link>
<router-view></router-view>
</div>
</template>
<script>
export default {
name: 'app',
mounted () {
console.log('Hello App')
}
}
</script>
I do not know what's wrong with the code, the <router-view> do not update when I change the route.
I think your app is not properly initialized yet. You are starting your app as follows:
new Vue({
router,
store,
...App
}).$mount('#app')
You have the spread operator ...App, which is not necessary - it is used to convert array items to function args, and not correct in this context. Instead you should use the render function as provided in webpack template :
/* eslint-disable-line no-new */
new Vue({
el: "#app",
store,
router,
render: h => h(App)
})
Also you have attempted to import loader in routes and index, which is not necessary if you are using vue-cli.
Maybe you can start with the webpack template as base and slowly add functionality one step at a time: start with route definitions and your route components, ensure that everything works, and finally add vuex.
$mount('#app') is fine, I think the problem is your routes.js
Try this instead:
import Index from './../views/index.vue'
const routes = [
{ path: '/index', name: 'index', component: Index }
]
And here is a working webpack template which is already configured vue-router and vuex properly, you can initialize this template via vue-cli, for your reference: https://github.com/CodinCat/vue-webpack-plus