【问题标题】:How to test head() in nuxt.js using jest如何使用 jest 在 nuxt.js 中测试 head()
【发布时间】:2020-05-14 18:26:53
【问题描述】:

我正在使用带有 Jest 的 Nuxt.js 进行单元测试。我在布局中添加了一个 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>

我试过了:

const wrapper = shallowMount(index)
wrapper.vm.head() <- fails

有什么建议吗?

【问题讨论】:

    标签: unit-testing vue.js jestjs nuxt.js


    【解决方案1】:

    在用于挂载组件的 Vue 实例中注入 vue-meta 插件。然后您可以使用wrapper.vm.$metaInfo 访问head() 数据。请参阅下面的示例。

    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')
      })
    })
    
    

    【讨论】:

    • 这是您认为行不通的 Nuxt 相关答案之一,但可以。考虑到测试 Nuxt 商店的难度,我完全预料到这个测试用例会令人伤脑筋。
    猜你喜欢
    • 1970-01-01
    • 2019-07-23
    • 1970-01-01
    • 1970-01-01
    • 2017-11-11
    • 2020-06-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多