Testing Vue components methods - javascript

I am starting with Vue.js and is really hard to find documentation about Unit Test.
I am trying to test components methods and builtin stuff as ready(). I can call those correctly but they internally have references to this object and this context is lost during testing time.
error
TypeError: this.$on is not a function
spec.js
import Vue from 'vue';
import Partners from 'components/main/partner/Partners';
describe.only('Partners.vue', () => {
it('should render with mocked partners', (cb) => {
Partners.ready(); // I get an error here because ready() is calling inside: this.$on(...)
cb(null);
});
});
component.vue
export default {
name: 'Partners',
data() {
return { };
},
methods: {
get() {
// ...
}
},
ready() {
this.$on('confirm', (confirm) => {
// ...
});
this.get();
}
};

I think ready() is depreciated along with Vue 1.0. Consider upgrading to Vue 2 (where mounted() replaces ready()).
To test your component, you need to initialize your component and a Vue instance, (and usually mount it, depending what you are doing).
Using the vue-webpack template (which uses Vue 2):
var ctor = Vue.extend(Partners)
var vm = new ctor()
vm.$mount()
now you can do things like vm.method(), and vm.mount() will automatically be called, etc.

Related

Vue 2 watch fails for mixin data property, but works if the component has the data property

I am trying to move some functionality to a vue mixin from the component, to be able to use it in multiple components.
This (simplified version of the code) works:
export default {
data() {
return {
file: {},
audioPlayer: {
sourceFile: null,
},
};
},
watch: {
'audioPlayer.SourceFile': function (nextFile) {
console.log('new sourceFile');
this.$data.file = nextFile;
},
}
}
But if I move the audioPlayer data object to a mixin, the watch does no longer fire.
Is this expected behavior?
N.b. I resolved this by directly making the 'file' data property into a computed value, which works in this particular case, but the behavior is still strange.
You need a lowercase s. sourceFile not SourceFile
watch: {
'audioPlayer.sourceFile': function (nextFile) {
console.log('new sourceFile');
this.$data.file = nextFile;
},
}

Vue.JS import custom module

I have created a module greatings.js like this one:
function greatings() {
this.hello = function() {
return 'hello!';
}
this.goodbye = function() {
return 'goodbye!';
}
}
module.exports = greatings;
Then I imported it into main.js in VUE.JS just like:
import greatings from './assets/js/greatings';
Vue.use(greatings);
Now I would like to use it in my components but if I do it I got an error:
mounted() {
this.greatings.hello();
}
ERROR: Error in mounted hook: "TypeError: Cannot read property 'hello' of undefined"
How to fix it and be able to use my greatings?
Thanks for any help!
greatings.js file should be like this
export default {
hello() {
return "hello";
},
goodbye() {
return "goodbye!";
}
};
and import in any file you want to use like this
import greatings from './assets/js/greatings';
and call any function do you want. remove this function Vue.use(greatings);
When using Vue.use() to register a custom plugin, it has to define an install() function, which is called by Vue. From docs:
A Vue.js plugin should expose an install method. The method will be called with the Vue constructor as the first argument, along with possible options.
See the provided example, for all the options you have when creating a custom plugin: https://v2.vuejs.org/v2/guide/plugins.html

How to add global funtions like Create, Methods, Mounted from a plugin in Vue?

For some cases, I don't want to use mixins in my Plugin.
I am trying to add a custom Methods like created(), mounted(), methods{}, so I can access its property when the component is loaded & run my custom method.
example: "customMethod"
// #root/home.vue
<script>
export default {
name: 'Home',
props: {
msg: String
},
mounted(){
//
},
methods{
//
},
customMethod{
}
}
</script>
.vue file
<script>
export default {
customMethod () { // Custom option.
console.log('custom method executed!')
},
methods: {},
created () {},
mounted () {}
}
</script>
plugins/customMethods.js
const customMethods = {
install (Vue) {
// INSTALL
if (this.installed) return
this.installed = true
Vue.options = Vue.util.mergeOptions(Vue.options, {
created: function () {
if (this.$options.customMethod) { // If found in the component.
this.$options.customMethod() // Execute the customMethod.
}
}
})
}
}
export default customMethods
main.js
import customMethods from 'plugins/customMethods.js'
Vue.use(customMethods)
What this does is extend the default options for all Vue instances so
the behavior is applied to every single Vue instance created. This is
however undocumented at the moment.
Alternatively, this can also be achieved by the use of global mixin in the plugin. (which you don't want for some reason as per your use case.)
Moreover, one advanced use case is we may need special handling when merging custom option values during Vue.extend. For example, the created hook has a special merge strategy that merges multiple hook functions into an Array so that all of them will be called. The default strategy is a simple overwrite. If you need a custom merge strategy you will need to register it under Vue.config.optionMergeStrategies:
Vue.config.optionMergeStrategies.customMethod = function (parentVal, childVal) {
// return merged value.
}
Every component can access your customMethod if you inject it into Vue.prototype like this:
Vue.prototype.customMethod = function() {}

Vue.js - How to call method from another component

I am using Vue.Js v2. I want to call component1->c1method in component2->c2method for reload data after submitting.
Vue.component('component1', {
methods: {
c1method: function(){
alert('this is c1method')
},
}
})
Vue.component('component2', {
methods: {
c2method: function(){
component('component1').c1method()//like this
},
}
})
For non-parent-child relation, then this is the same as this one. Call one method, apparently any method of a component from any other component. Just add a $on function to the $root instance and call form any other component accessing the $root and calling $emit function.
On First component
....
mounted() {
this.$root.$on('component1', () => {
// your code goes here
this.c1method()
}
}
and in the second component call the $emit function in $root
...
c2method: function(){
this.$root.$emit('component1') //like this
},
It acts more like a socket. Reference here
https://stackoverflow.com/a/50343039/6090215
// Component A
Vue.component('A', {
created() {
this.$root.$refs.A = this;
},
methods: {
foo: function() {
alert('this is A.foo');
}
}
});
// Component B
Vue.component('B', {
methods: {
bar: function() {
this.$root.$refs.A.foo();
}
}
});
No need for hacky solutions.
In vuejs we can create events that can be listened globally.
With this feature, whenever we want to call our beloved function, we just emit this event.
Now, we just listen to this event all the time from the component. whenever this global event happens we can execute our method we want to call.
It's pretty simple:
you go to main.js, before creating the vue instance, write this:
export const eventBus = new Vue(); // added line
new Vue({
...
...
...
render: h => h(App)
}).$mount('#app');
Anywhere we want to fire the target function, we dont fire it, we just emit this event:
eventBus.$emit('fireMethod');
Now in our component that has the target function, we always listen to this event:
created() {
eventBus.$on('fireMethod', () => {
this.myBelovedMethod();
})
}
Dont forget to import eventBus in top.
import {eventBus} from "path/to/main.js";
thats it, few lines of code, no hacky, all vuejs power.
The docs address this situation
https://v2.vuejs.org/v2/guide/components.html#Non-Parent-Child-Communication
If your components have the same parent, you can emit an event that the parent listens to. Then with the ref property set, you can call the c1method from the parent.
https://v2.vuejs.org/v2/guide/components.html#Child-Component-Refs
Try this out.
<template>
...
<component1 ref='componentOne'>
...
</template>
<script>
Vue.component('component2', {
methods: {
c2method: function(){
this.$refs.componentOne.c1method();
}
}
});
</script>
If anyone is looking for a solution in Vue.js v3:
https://v3-migration.vuejs.org/breaking-changes/events-api.html#event-bus
https://github.com/developit/mitt#install
import mitt from 'mitt'
const emitter = mitt()
// listen to an event
emitter.on('foo', e => console.log('foo', e) )
// listen to all events
emitter.on('*', (type, e) => console.log(type, e) )
// fire an event
emitter.emit('foo', { a: 'b' })
// clearing all events
emitter.all.clear()

Running a function in a VueJs 2 component once its loaded

How do I fetch data once a component has been mounted? I start my vue instance and then load in the component, the component template loads in fine but the function calls in mounted are never run so the stats object remains empty, in turn, causing errors in the component/template that requires the data.
So how do I run a certain function on component load?
For what its worth... the functions I want to call will all make REST requests but each component will be running different requests.
Vue.component('homepage', require('./components/Homepage.vue'), {
props: ["stats"],
mounted: function() {
this.fetchEvents();
console.log('afterwards');
},
data: {
loading: true,
stats: {}
},
methods: {
fetchEvents: function() {
this.$http.get('home/data').then(function(response) {
this.stats = response.body;
this.loading = false;
}, function(error) {
console.log(error);
});
}
}
});
const vue = new Vue({
el: '#main',
mounted: function() {
console.log('main mounted');
}
});
You are already doing it fine by putting all the initialization stuff into mounted. The reason your component is not refreshing is probably because of binding of this, as explained below:
In your fetchEvents function, your $http success handler provides a response, which you are attempting to assign to this.stats. But it fails because this points to that anonymous function scope and not to Vue component.
To overcome this issue, you may use arrow functions as shown below:
fetchEvents: function() {
this.$http.get('home/data').then(response => {
this.stats = response.body;
this.loading = false;
}, error => {
console.log(error);
});
}
Arrow functions do not create its own scope or this inside. If you use this inside the arrow function as shown above, it still points to Vue component, and therefore your component will have its data updated.
Note: Even the error handler needs to use arrow function, so that you may use this (of Vue component) for any error logging.

Categories