Reputation: 356
I am using Nuxt.js with Jest for unit testing. I added a head function in my layout to change the title and I would like to unit test it. Here is my file:
<template>
<h1 class="title">HELLO</h1>
</template>
<script>
export default {
data () {
return {
title: 'MY TITLE'
}
},
head () {
return {
title: this.title,
meta: [
{ hid: 'description', name: 'description', content: 'MY DESCRIPTION' }
]
}
}
}
</script>
I tried:
const wrapper = shallowMount(index)
wrapper.vm.head() <- fails
Any suggestions?
Upvotes: 3
Views: 3006
Reputation: 28
head() can be accessed by:
wrp.vm.$options.head()
Another, maybe better way for testing is to extract function to separate file.
Upvotes: 0
Reputation: 332
Inject vue-meta
plugin in the Vue instance used for mounting the component. You can then access head()
data with wrapper.vm.$metaInfo
. See example below.
pageOrLayoutToTest.vue
<template>
<h1 class="title">HELLO</h1>
</template>
<script>
export default {
data () {
return {
title: 'MY TITLE'
}
},
head () {
return {
title: this.title,
meta: [
{ hid: 'description', name: 'description', content: 'MY DESCRIPTION' }
]
}
}
}
</script>
pageOrLayoutToTest.spec.js
import { shallowMount, createLocalVue } from '@vue/test-utils'
import VueMeta from 'vue-meta'
// page or layout to test
import pageOrLayoutToTest from '@/path/to/pageOrLayoutToTest.vue'
// create vue with vue-meta
const localVue = createLocalVue()
localVue.use(VueMeta, { keyName: 'head' })
describe('pageOrLayoutToTest.vue', () => {
let wrapper;
// test set up
beforeEach(() => {
wrapper = shallowMount(pageOrLayoutToTest, {
localVue
})
})
// test tear down
afterEach(() => {
if (wrapper) {
wrapper.destroy()
}
})
it('has correct <head> content', () => {
// head data injected by the page or layout to test is accessible with
// wrapper.vm.$metaInfo. Note that this object will not contain data
// defined in nuxt.config.js.
// test title
expect(wrapper.vm.$metaInfo.title).toBe('MY TITLE')
// test meta entry
const descriptionMeta = wrapper.vm.$metaInfo.meta.find(
(item) => item.hid === 'description'
)
expect(descriptionMeta.content).toBe('MY DESCRIPTION')
})
})
Upvotes: 6