Как проверить head () в nuxt. js используя jest - PullRequest
0 голосов
/ 29 января 2020

Я использую 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>

Я пытался:

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

Есть предложения?

1 Ответ

1 голос
/ 14 апреля 2020
Плагин

Inject 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>

pageOrLayoutToTest.spe c. 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
    // definedin 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')
  })
})

...