Ayo*_*oub 3 unit-testing vue.js jestjs nuxt.js
我使用 Nuxt.js 和 Jest 进行单元测试。我在布局中添加了一个 head 函数来更改标题,我想对其进行单元测试。这是我的文件:
<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>Run Code Online (Sandbox Code Playgroud)
我试过:
const wrapper = shallowMount(index)
wrapper.vm.head() <- fails
Run Code Online (Sandbox Code Playgroud)
有什么建议么?
vue-meta在用于安装组件的 Vue 实例中注入插件。然后您可以使用 访问head()数据wrapper.vm.$metaInfo。请参阅下面的示例。
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>
Run Code Online (Sandbox Code Playgroud)
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')
})
})
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2769 次 |
| 最近记录: |