如何使用jest测试nuxt?

3

我正在学习使用 jest 进行 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"
1个回答

7

目前还没有一个库可以在vue-test-utils中扩展nuxt组件结构。

尽管如此,你可以使用mocks api轻松自己实现一些功能。

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

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


由于我们从 $options 获取引用,所以我必须将 this 调整到正确的上下文,对我来说有效的是 await wrapper.vm.$options.fetch.apply(wrapper.vm, []) - Jesus Monzon Legido

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接