我正在学习使用 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"
$options
获取引用,所以我必须将this
调整到正确的上下文,对我来说有效的是await wrapper.vm.$options.fetch.apply(wrapper.vm, [])
。 - Jesus Monzon Legido