如何用玩笑测试nuxt?

我只是在开玩笑地学习 Nuxt。我的test.vue。刚刚从https://nuxtjs.org/docs/2.x/features/data-fetching复制

<template>
  <div>
    <h1 class="page-title">Mountains</h1>
    <p v-if="$fetchState.pending">Fetching mountains...</p>
    <p v-else-if="$fetchState.error">An error occurred :(</p>
    <div v-else>
      <h1>Nuxt Mountains</h1>
      <ul>
        <li v-for="mountain of mountains">{{ mountain.title }}</li>
      </ul>
      <button @click="$fetch">Refresh</button>
    </div>
  </div>
</template>
<script>
export default {
  data () {
    return {
      mountains: [],
    }
  },
  async fetch () {
    this.products = await fetch(
       'https://api.nuxtjs.dev/mountains'
    ).then(res => res.json())
  }
}
</script>

我的 test.spec.js

import { mount } from '@vue/test-utils'
import Test from '@/components/test.vue'

describe('Test', () => {
  test('is a Vue instance', () => {
    const wrapper = mount(Test)
    const title = wrapper.find('.page-title')
    expect(title.text()).toBe("Mountains")
  })
})

当我运行 npm run test 时,我收到了这个错误。我该如何解决这个问题?

[Vue warn]: Error in render: "TypeError: Cannot read property 'pending' of undefined"

回答

目前没有库来扩展 vue-test-utils 中的 nuxt 组件结构。

话虽如此,您可以使用模拟 api 很容易地自己做一些事情。

mounted(Component, { mocks: { $fetchState: { pending: true, error: true, timestamp: Date.now() } } })

真正棘手的部分是在组件中找不到 fetch。您可以在选项中找到它,wrapper.vm.$options.fetch()但目前还没有真正的测试方法......


以上是如何用玩笑测试nuxt?的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>