ReferenceError: contenuto_translated is not defined - vue.js

I'm stuck at this error that I get only if I run my laravel + vuejs in build mode.
Ihave a custom component with 3 input and I'm using it in a Quasar dialog. When I start typing inside one of these 3 inputs, it give me the error I wrote in the post title.
See code and details.
I have a custom component file (EditObjectTranslation_Singleline.vue)
<template>
<q-dialog ref="dialogRef" #hide="onDialogHide">
<q-card class="q-dialog-plugin">
<!--
...content
... use q-card-section for it?
-->
<q-card-section>
<div class="text-h6">{{ titolo }}</div>
<q-form #submit.prevent="invia_form">
<div>
<q-input outlined v-model="contenuto_campo" label="Contenuto CAMPO" class="mt-4 block w-full" :disable="true"/>
</div>
<div>
<q-input outlined v-model="contenuto_lingua_default" label="Contenuto Lingua IT" class="mt-4 block w-full" :disable="true"/>
</div>
<div>
<q-input outlined v-model="contenuto_translated" :label="label_translated" class="mt-4 block w-full" :maxlength="max_lunghezza"/>
</div>
</q-form>
</q-card-section>
<!-- buttons example -->
<q-card-actions align="right">
<q-btn color="primary" label="OK" #click="onOKClick" />
<q-btn color="primary" label="Cancel" #click="onDialogCancel" />
</q-card-actions>
</q-card>
</q-dialog>
</template>
<script setup>
import { useDialogPluginComponent } from 'quasar'
import { computed } from '#vue/reactivity'
const props = defineProps({
contenuto_campo: '',
contenuto_lingua_default: '',
contenuto_translated: '',
lingua: '',
max_lunghezza: 0
})
const label_translated = computed (() => {
return "Contenuto tradotto " + props.lingua
})
defineEmits([
// REQUIRED; need to specify some events that your
// component will emit through useDialogPluginComponent()
...useDialogPluginComponent.emits
])
const { dialogRef, onDialogHide, onDialogOK, onDialogCancel } = useDialogPluginComponent()
// dialogRef - Vue ref to be applied to QDialog
// onDialogHide - Function to be used as handler for #hide on QDialog
// onDialogOK - Function to call to settle dialog with "ok" outcome
// example: onDialogOK() - no payload
// example: onDialogOK({ /*...*/ }) - with payload
// onDialogCancel - Function to call to settle dialog with "cancel" outcome
// this is part of our example (so not required)
function onOKClick () {
// on OK, it is REQUIRED to
// call onDialogOK (with optional payload)
onDialogOK(props)
// or with payload: onDialogOK({ ... })
// ...and it will also hide the dialog automatically
}
</script>
Then, I want to use the previous component as a custom component in a quasar dialog.
So the page code where I'm using the previous custom components follows
<script setup>
import AuthenticatedLayout from '#/Layouts/AuthenticatedLayout.vue';
import { Inertia } from '#inertiajs/inertia';
import { useQuasar } from 'quasar';
import { ref } from 'vue';
import { computed } from '#vue/reactivity';
import { Link } from '#inertiajs/inertia-vue3';
import CustomComponent from '#/Components/EditObjectTranslation_Singleline.vue';
import axios from 'axios';
const $q = useQuasar()
const props = defineProps({
catalogues: Array,
lingue: Array,
field2betranslated: Number
})
const $qTranslate = useQuasar()
function onTranslateObject (pLingua) {
if (selected.value.length > 0 ) {
axios
.get('/api/getTraduzioni/'+ pLingua + '/' + selected.value[0].resource_id)
.then((response) => {
$q.dialog({
component: CustomComponent,
componentProps: {
titolo: 'Traduci contenuti:',
contenuto_campo: selected.value[0].name,
contenuto_lingua_default: response.data.originale,
contenuto_translated: response.data.tradotto,
lingua: pLingua,
max_lunghezza: 64,
resource_id: selected.value[0].resource_id
// ...more..props...
}
}).onOk((formData) => {
// console.log('>>>> OK')
translateObject(formData)
}).onOk(() => {
// console.log('>>>> second OK catcher')
}).onCancel(() => {
// console.log('>>>> Cancel')
}).onDismiss(() => {
// console.log('I am triggered on both OK and Cancel')
})
})
} else {
$q.dialog({
title: 'Attenzione',
message: 'Devi selezionare una riga'
})
}
}
</script>
<template>
<Head :title="$t('cataloghi.pagetitle') " />
<AuthenticatedLayout>
<div class="q-py-xl">
<!-- Pulsanti traduzioni -->
<div class="w-full flex justify-end space-x-2 mb-4">
<q-btn v-for="lingua in lingue" :label="lingua.codiceIso" :key="lingua.codiceIso" #click="onTranslateObject(lingua.codiceIso)" icon="language" color="whte" text-color="text-grey-7" />
</div>
</div>
</AuthenticatedLayout>
</template>
When I open the dialog and try to input in the "contenuto_translated" q-input I get this error:
"ReferenceError: contenuto_translated is not defined"
Surely I'm missing something.
Please help me.

Related

Show on click / hide on blur wrapper component

I have several widgets that I'd like to toggle on click/blur/submit.
Let's take a simple example with an input (Vue 2 style)
Input.vue
<template>
<input
ref="input"
:value="value"
#input="input"
#blur="input"
#keyup.escape="close"
#keyup.enter="input"
/>
</template>
<script>
export default {
props: ['value'],
methods: {
input() {
this.$emit("input", this.$refs.text.value);
this.close();
},
close() {
this.$emit("close");
},
}
}
</script>
ToggleWrapper.vue
<template>
<div #click="open = true">
<div v-if="open">
<slot #close="open = false"></slot> <!-- Attempt to intercept the close event -->
</div>
</div>
</template>
<script>
export default {
data() {
return {
open: false,
}
},
}
</script>
Final usage:
<ToggleWrapper>
<Input v-model="myText" #submit="updateMyText" />
</ToggleWrapper>
So when I click on ToggleWrapper it appears, but if I close it, it doesn't disappear because it's not getting the close event.
Should I use scoped events ?
How can I intercept the close event by adding the less possible markup on the final usage ?
I think it makes sense to use a scoped slot to do this. But you can also try this kind of solution.
Input.vue
<template>
<input
ref="input"
:value="value"
#input="input"
#blur="input"
#keyup.escape="close"
#keyup.enter="input"
/>
</template>
<script>
export default {
props: ['value'],
methods: {
input() {
this.$emit("input", this.$refs.text.value);
this.close();
},
close() {
this.$parent.$emit('close-toggle')
},
}
}
</script>
ToggleWrapper.vue
<template>
<div #click="open = true">
Click
<div v-if="open">
<slot></slot> <!-- Attempt to intercept the close event -->
</div>
</div>
</template>
<script>
export default {
data() {
return {
open: false,
}
},
created() {
this.$on('close-toggle', function () {
this.open = false
})
}
}
</script>
In a Vue3 style, I would use provide and inject (dependency injection). This solution leaves the final markup very light and you still have a lot of control, see it below :
Final usage :
<script setup>
import { ref } from 'vue'
import ToggleWrapper from './ToggleWrapper.vue'
import Input from './Input.vue'
const myText = ref('hi')
const updateMyText = ($event) => {
myText.value = $event
}
</script>
<template>
<ToggleWrapper>
<Input :value="myText" #submit="updateMyText" />
</ToggleWrapper>
<p>value : {{myText}}</p>
</template>
ToggleWrapper.vue
<template>
<div #click="open = true">
<div v-if="open">
<slot></slot>
</div>
<span v-else>Open</span>
</div>
</template>
<script setup>
import { provide, inject, ref } from 'vue'
const open = ref(false)
provide('methods', {
close: () => open.value = false
})
</script>
Input.vue
<template>
<input
:value="value"
#input="input"
#blur="close"
#keyup.escape="close"
#keyup.enter="submit"
/>
</template>
<script setup>
import { inject, ref } from 'vue'
const props = defineProps(['value'])
const emit = defineEmits(['close', 'input', 'submit'])
const methods = inject('methods')
const value = ref(props.value)
const input = ($event) => {
value.value = $event.target.value
emit("input", $event.target.value);
}
const close = () => {
methods.close()
emit('close')
}
const submit = () => {
emit('submit', value.value)
close()
}
</script>
See it working here

how can I get the data from localStorage to show in homePosts vue.js compositions API

I'm doing a simple blog app to practice vue.js. I'm using composition API. I have stored data that get filled in in a form. This data I want to print out in another component homePosts where you can see the written blogpost with writer, headline and blogtext. I have used v-model, stored data to localStorage, in homePosts I have used v-for and {{ }} syntax to get data. But nothing shows in homePosts.
Can someone please see what im missing.
writePost.vue
<template>
<div>
<form class="form">
<label for="writer">Writer name: </label>
<input v-model="newWriter" type="text" max="500" />
<br />
<label for="img">Select image:</label>
<input type="file" id="img" name="img" accept="image/*" />
<br />
<label for="headline">Headline </label>
<input v-model="newHeadline" type="text" max="500" />
<label>Your blogtext: </label>
<textarea v-model="newNote" name="" id="" cols="30" rows="30"></textarea>
<button type="submit" #click="addNote" class="button"><router-link to="/homePosts" class="link">Post blog</router-link></button>
</form>
</div>
</template>
<script setup>
import { ref } from "vue";
const newNote = ref("");
const newWriter = ref("");
const newHeadline = ref("");
const notes = ref([]);
const addNote = () => {
notes.value.push({
id: Math.floor(Math.random() * 1000000),
text: newNote.value,
writer: newWriter.value,
headline: newHeadline.value,
});
addLocalStorage(notes)
};
const addLocalStorage = (notes) => {
localStorage.setItem("notes", JSON.stringify(notes))
JSON.parse(localStorage.getItem("notes"));
}
</script>
homePosts.vue
<template>
<div class="post-container">
<h1>Blog Posts</h1>
<div class="post-mini-container" >
<div class="post" v-for="note in notes" :key="note.id">
<!-- <img class="img-post" src="#/assets/person1.jpg"> -->
<p class="writer"> {{ note.writer }}</p>
<p class="headline"> {{ note.headline }}</p>
<p class="blog-text" > {{ note.text }}</p>
</div>
</div>
</div>
</template>
<script>
export default {
name: 'homePosts'
}
</script>
You need to start your ref already parsing the existing items in your localStorage.
const notes = ref(JSON.parse(localStorage.getItem('notes') ?? '[]');
Or better yet, use a computed getter/setter:
const notes = computed({
get: () => JSON.parse(localStorage.getItem('notes') ?? '[]'),
set: (value) => {
localStorage.setItem('notes', JSON.stringify(value))
}
});
Or even better, take a look at vueUse/useLocalStorage 🎉
there are two approaches that you can follow, "event bus" or "pinia / vuex".
i'll explain how you can implement event bus
(you can check this post for inspiration: https://medium.com/#certosinolab/using-event-bus-in-vue-js-3-425aae8c21a6)
Add global event bus
install mit: npm install --save mitt
go to your main.ts / main.js and add the global property
import mitt from 'mitt';
const dispatcher = mitt();
const app = createApp(App);
app.config.globalProperties.dispatcher = dispatcher;
app.mount('#app');
update "script" content in writePost.vue component
<script setup>
import { ref , getCurrentInstance } from "vue";
const app = getCurrentInstance();
const dispatcher= app?.appContext.config.globalProperties.dispatcher;
const newNote = ref("");
const newWriter = ref("");
const newHeadline = ref("");
const notes = ref([]);
const addNote = () => {
notes.value.push({
id: Math.floor(Math.random() * 1000000),
text: newNote.value,
writer: newWriter.value,
headline: newHeadline.value,
});
// emit notes
dispatcher.emit("updateNotes" , notes);
addLocalStorage(notes)
};
const addLocalStorage = (notes) => {
localStorage.setItem("notes", JSON.stringify(notes))
JSON.parse(localStorage.getItem("notes"));
}
</script>
update "script" content in homePosts.vue component
<script>
export default {
name: 'homePosts',
data() {
return {notes: []}
},
mounted() {
this.notes = JSON.parse(localStorage.getItem("notes") ?? "[]");
this.dispatcher.on("updateNotes" , (notes) => {
this.notes = notes ?? [];
})
},
beforeDestroy() {
this.dispatcher.off("updateNotes");
},
}
</script>

Unable to Define Variable in Vue

I'm just starting to use VueJS & Tailwind, having never really used anything related to npm before.
I have the below code, making use of Tailwind & Headless UI which through debugging, I know I'm like 99% of the way there... except for the continuous error message
Uncaught ReferenceError: posts is not defined
I know this should be straight forward, but everything I've found either here or with Google hasn't worked. Where am I going wrong?
<template>
<Listbox as="div" v-model="selected">
<ListboxLabel class="">
Country
</ListboxLabel>
<div class="mt-1 relative">
<ListboxButton class="">
<span class="">
<img :src="selected.flag" alt="" class="" />
<span class="">{{ selected.name }}</span>
</span>
<span class="">
<SelectorIcon class="" aria-hidden="true" />
</span>
</ListboxButton>
<transition leave-active-class="" leave-from-class="opacity-100" leave-to-class="opacity-0">
<ListboxOptions class="">
<ListboxOption as="template" v-for="country in posts" :key="country" :value="country" v-slot="{ active, selected }">
<li :class="">
<div class="">
<img :src="country.flag" alt="" class="" />
<span :class="[selected ? 'font-semibold' : 'font-normal', 'ml-3 block truncate']">
{{ country.latin }}
</span>
</div>
<span v-if="selected" :class="">
<CheckIcon class="" aria-hidden="true" />
</span>
</li>
</ListboxOption>
</ListboxOptions>
</transition>
</div>
</Listbox>
</template>
<script>
import { ref } from 'vue'
import { Listbox, ListboxButton, ListboxLabel, ListboxOption, ListboxOptions } from '#headlessui/vue'
import { CheckIcon, SelectorIcon } from '#heroicons/vue/solid'
import axios from 'axios'
export default {
data() {
return {
response: null,
posts: undefined,
};
},
components: {
Listbox,
ListboxButton,
ListboxLabel,
ListboxOption,
ListboxOptions,
CheckIcon,
SelectorIcon,
},
mounted: function() {
axios.get('http://localhost')
.then(response => {
this.posts = response.data;
});
},
setup() {
const selected = ref(posts[30])
return {
selected,
}
},
}
</script>
The offending line is const selected = ref(posts[30]) which I know I need to somehow define posts, but I don't get how?
CAUSE OF YOUR ERROR:
You are trying to access an array element before the array is populated. Thus the undefined error.
EXPLANATION
You are using a mix of composition api and options api. Stick to one.
I am writing this answer assuming you will pick the composition api.
Follow the comments in the below snippet;
<script>
// IMPORT ONMOUNTED HOOK
import { ref, onMounted } from 'vue'
import { Listbox, ListboxButton, ListboxLabel, ListboxOption, ListboxOptions } from '#headlessui/vue'
import { CheckIcon, SelectorIcon } from '#heroicons/vue/solid'
import axios from 'axios'
export default {
// YOU DO NOT NEED TO DEFINE THE DATA PROPERTY WHEN USING COMPOSITION API
/*data() {
return {
response: null,
posts: undefined,
};
},*/
components: {
Listbox,
ListboxButton,
ListboxLabel,
ListboxOption,
ListboxOptions,
CheckIcon,
SelectorIcon,
},
// YOU DO NOT NEED THESE LIFE CYCLE HOOKS; COMPOSITION API PROVIDES ITS OWN LIFECYCLE HOOKS
/*mounted: function() {
axios.get('http://localhost')
.then(response => {
this.posts = response.data;
});
},*/
setup() {
// YOU ARE TRYING TO ACCESS AN ELEMENT BEFORE THE ARRAY IS POPULATED; THUS THE ERROR
//const selected = ref(posts[30])
const posts = ref(undefined);
const selected = ref(undefined);
onMounted(()=>{
// CALL THE AXIOS METHOD FROM WITHIN THE LIFECYCLE HOOK AND HANDLE THE PROMISE LIKE A BOSS
axios.get('http://localhost')
.then((res) => {
selected.value = res[30];
});
});
return {
selected,
}
},
}
</script>
According to your comment; you should first check if the “selected != null” before using ‘selected’ inside the template. You can use a shorthand version like this
<img :src=“selected?.flag” />

(Vue) I have problems reusing references from a composable function

I hope it is okay that I included my full code. Otherwise it would be difficult to understand my question.
I have made a composable function for my Vue application, which purpose is to fetch a collection of documents from a database.
The composable looks like this:
import { ref, watchEffect } from 'vue'
import { projectFirestore } from '../firebase/config'
const getCollection = (collection, query) => {
const documents = ref(null)
const error = ref(null)
let collectionRef = projectFirestore.collection(collection)
.orderBy('createdAt')
if (query) {
collectionRef = collectionRef.where(...query)
}
const unsub = collectionRef.onSnapshot(snap => {
let results = []
snap.docs.forEach(doc => {
doc.data().createdAt && results.push({ ...doc.data(), id: doc.id })
})
documents.value = results
error.value = null
}, (err) => {
console.log(err.message)
document.value = null
error.value = 'could not fetch data'
})
watchEffect((onInvalidate) =>{
onInvalidate(() => unsub());
});
return {
documents,
error
}
}
export default getCollection
Then I have a component where I store the data from the database
<template>
<div v-for="playlist in playlists" :key="playlist.id">
<div class="single">
<div class="thumbnail">
<img :src="playlist.coverUrl">
</div>
<div class="info">
<h3>{‌{ playlist.title }}</h3>
<p>created by {‌{ playlist.userName }}</p>
</div>
<div class="song-number">
<p>{‌{ playlist.songs.length }} songs</p>
</div>
</div>
</div>
</template>
<script>
export default {
// receiving props
props: ['playlists'],
}
</script>
And finally, I output the data inside the main Home component, where I use the documents and error reference from the composable file.
<template>
<div class="home">
<div v-if="error" class="error">Could not fetch the data</div>
<div v-if="documents">
<ListView :playlists="documents" />
</div>
</div>
</template>
<script>
import ListView from '../components/ListView.vue'
import getCollection from '../composables/getCollection'
export default {
name: 'Home',
components: { ListView },
setup() {
const { error, documents } = getCollection('playlists')
return { error, documents }
}
}
</script>
That is all well and good.
But now I wish to add data from a second collection called "books", and the idea is to use the same composable to fetch the data from that collection as well,
but the problem is that inside the Home component, I cannot use the references twice.
I cannot write:
<template>
<div class="home">
<div v-if="error" class="error">Could not fetch the data</div>
<div v-if="documents">
<ListView :playlists="documents" />
<ListView2 :books="documents" />
</div>
</div>
</template>
export default {
name: 'Home',
components: { ListView, ListView2 },
setup() {
const { error, documents } = getCollection('playlists')
const { error, documents } = getCollection('books')
return { error, documents }
}
}
This will give me an error because I reference documents and error twice.
So what I tried was to nest these inside the components themselves
Example:
<template>
<div v-for="playlist in playlists" :key="playlist.id">
<div class="single">
<div class="thumbnail">
<img :src="playlist.coverUrl">
</div>
<div class="title">
{{ playlist.title }}
</div>
<div class="description">
{{ playlist.description }}
</div>
<div>
<router-link :to="{ name: 'PlaylistDetails', params: { id: playlist.id }}">Edit</router-link>
</div>
</div>
</div>
</template>
<script>
import getCollection from '../composables/getCollection'
export default {
setup() {
const { documents, error } = getCollection('playlists')
return {
documents,
error
}
}
}
</script>
This does not work either.
I will just get a 404 error if I try to view this component.
So what is the correct way of writing this?
Try out to rename the destructed fields like :
const { error : playlistsError, documents : playlists } = getCollection('playlists')
const { error : booksError, documents : books } = getCollection('books')
return { playlistsError, playlists , booksError , books }

Use more than one directive to add data attributes to components

I have two directives which are supposed to add data attributes to components for testing, however, only one of the directives actually gets added. The two components are Bootstrap-Vue's BFormInput and BButton.
I tried removing everything but one of the buttons and the directive is still not added i.e
<b-input-group class="sm-2 mb-2 mt-2">
<b-button
variant="primary"
#click="searchJobs"
class="rounded-0"
v-jobs-search-button-directive="{ id: 'search-button' }"
>
Search
</b-button>
</b-input-group>
wrapper.html() output is:
<b-input-group-stub tag="div" class="sm-2 mb-2 mt-2"><b-button-stub target="_self" event="click" routertag="a" variant="secondary" type="button" tag="button" class="rounded-0">
Search
</b-button-stub></b-input-group-stub>
However, it is added when instead of a button I leave in place the input form i.e.
<b-input-group class="sm-2 mb-2 mt-2">
<b-form-input
v-jobs-search-input-directive="{ id: 'input-keyword' }"
class="mr-2 rounded-0"
placeholder="Enter Search term..."
:value="this.searchConfig.Keyword"
#input="this.updateJobsSearchConfig"
/>
</b-input-group>
wrapper.html() output is:
<b-input-group-stub tag="div" class="sm-2 mb-2 mt-2"><b-form-input-stub value="" placeholder="Enter Search term..." type="text" class="mr-2 rounded-0" data-jobs-search-input-id="input-keyword"></b-form-input>
This is how I add the directives
<template>
<b-input-group class="sm-2 mb-2 mt-2">
<b-form-input
v-jobs-search-input-directive="{ id: 'input-keyword' }"
class="mr-2 rounded-0"
placeholder="Enter Search term..."
:value="this.searchConfig.Keyword"
#input="this.updateJobsSearchConfig"
/>
<b-button
variant="primary"
#click="searchJobs"
class="rounded-0"
v-jobs-search-button-directive="{ id: 'search-button' }"
>
Search
</b-button>
</b-input-group>
</template>
<script>
import { mapActions, mapState } from 'vuex'
import JobService from '#/api-services/job.service'
import JobsSearchInputDirective from '#/directives/components/jobs/JobsSearchInputDirective'
import JobsSearchButtonDirective from '#/directives/components/jobs/JobsSearchButtonDirective'
export default {
name: 'jobs-search',
directives: { JobsSearchInputDirective, JobsSearchButtonDirective },
data () {
return {
jobs: [],
pages: 0
}
},
computed: {
...mapState({
pagedConfig: state => state.jobs.paged,
searchConfig: state => state.jobs.search
})
},
methods: {
// Methods go here
}
}
jobs-search-input-directive is
export default (el, binding) => {
if (process.env.NODE_ENV === 'test') {
Object.keys(binding.value).forEach(value => {
el.setAttribute(`data-jobs-search-input-${value}`, binding.value[value])
})
}
}
jobs-search-button-directive is
export default (el, binding) => {
if (process.env.NODE_ENV === 'test') {
Object.keys(binding.value).forEach(value => {
el.setAttribute(`data-jobs-search-button-${value}`, binding.value[value])
})
}
}
This is the test I run, mounting with shallowMount
it('should call jobsSearch method on search button click event', () => {
wrapper.find('[data-jobs-search-button-id="search-button"]').trigger('click')
expect(searchJobs).toHaveBeenCalled()
})
which comes back with
Error: [vue-test-utils]: find did not return [data-jobs-search-button-id="search-button"], cannot call trigger() on empty Wrapper
However wrapper.find('[data-jobs-search-input-id="input-keyword"]') DOES find the input-form
The two directives are registered in the JobsSearch.vue component and they definitely get rendered if I remove the process.env part
I expect the attribute to be added to both components but it only gets added to the BFormInput when testing. Any help will be greatly appreciated.
I believe that the problem occurs when...
... trying to use a directive...
... on a functional child component...
... with shallowMount.
b-button is a functional component.
I've put together the demo below to illustrate the problem. It mounts the same component in 3 different ways and it only fails in the specific case outlined above.
MyComponent = {
template: `
<div>
<my-normal v-my-directive></my-normal>
<my-functional v-my-directive></my-functional>
</div>
`,
components: {
MyNormal: {
render: h => h('span', 'Normal')
},
MyFunctional: {
functional: true,
render: (h, context) => h('span', context.data, 'Functional')
}
},
directives: {
myDirective (el) {
el.setAttribute('name', 'Lisa')
}
}
}
const v = new Vue({
el: '#app',
components: {
MyComponent
}
})
document.getElementById('markup1').innerText = v.$el.innerHTML
const cmp1 = VueTestUtils.mount(MyComponent)
document.getElementById('markup2').innerText = cmp1.html()
const cmp2 = VueTestUtils.shallowMount(MyComponent)
document.getElementById('markup3').innerText = cmp2.html()
#markup1, #markup2, #markup3 {
border: 1px solid #777;
margin: 10px;
padding: 10px;
}
<script src="https://unpkg.com/vue#2.6.10/dist/vue.js"></script>
<script src="https://unpkg.com/vue-template-compiler#2.6.10/browser.js"></script>
<script src="https://unpkg.com/#vue/test-utils#1.0.0-beta.29/dist/vue-test-utils.iife.js"></script>
<div id="app">
<my-component></my-component>
</div>
<div id="markup1"></div>
<div id="markup2"></div>
<div id="markup3"></div>
I haven't really looked at the code for vue-test-utils before but stepping through in the debugger makes me suspicious of this line:
https://github.com/vuejs/vue-test-utils/blob/9dc90a3fd4818ff70e270568a2294b1d8aa2c3af/packages/create-instance/create-component-stubs.js#L99
This is the render function for the stubbed child component. It would appear that context.data.directives does contain the correct directive but they aren't being passed on in the call to h.
Contrast that with the render function in my example component MyFunctional, which passes on all of data. That's required for directives to work with a functional component but when MyFunctional gets replaced with a stub the new render function seems to drop the directives property.
The only workaround I've been able to come up with is to provide your own stub:
VueTestUtils.shallowMount(MyComponent, {
stubs: {
BButton: { render: h => h('div')}
}
})
By using a non-functional stub the directive works fine. Not sure how much value this would take away from the test though.