如何用 jest 测试 nuxt?

Posted

技术标签:

【中文标题】如何用 jest 测试 nuxt?【英文标题】:How to test nuxt with jest? 【发布时间】:2021-03-17 19:23:13 【问题描述】:

我只是在开玩笑地学习 Nuxt。 我的测试.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】:

目前在 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, [])

以上是关于如何用 jest 测试 nuxt?的主要内容,如果未能解决你的问题,请参考以下文章