JS新手在这里。
我已经生成了一个 Nuxt 应用程序并实现了 @nuxt/auth
我的全局中间件 nuxt.config.js
.它在我的应用程序中按预期工作。
现在我想测试一些引用 $auth
的组件。目的。
// ~/components/hello_component.vue
<template>
<div>
<div v-if="$auth.loggedIn">
<h1>Hi, {{ userName }}</h1>
</div>
</div>
</template>
<script>
export default {
data () {
userName: "Archduke Chocula"
}
}
</script>
我有一个看起来像这样的测试:
// ~/spec/components/hello_component.spec.js
import { mount } from '@vue/test-utils'
import Hello from '@/components/hello_component.vue'
describe('Hello Component', () => {
test('is a Vue instance', () => {
const wrapper = mount(Hello)
expect(wrapper.isVueInstance()).toBeTruthy()
})
})
这导致以下错误
Error in render: "TypeError: Cannot read property 'loggedIn' of undefined"
很明显我需要在某处定义身份验证,所以我的问题是:
loggedIn
的响应方法以便我可以测试我登录/注销的场景? 在此先感谢您的帮助!
最佳答案
您可以通过在 options 中传递模拟来模拟您的 $auth 对象。调用时的对象 mount
import { mount } from '@vue/test-utils'
import Hello from '@/components/hello_component.vue'
const authMock = {
loggedIn: true
};
describe('Hello Component', () => {
test('is a Vue instance', () => {
const wrapper = mount(Hello, {
mocks: {
$auth: authMock
}
})
expect(wrapper.isVueInstance()).toBeTruthy()
})
})
您可以根据自己的喜好扩展模拟,或者更改它为每个测试返回的值。
关于unit-testing - 使用 Jest 在 Nuxt 中测试组件时如何添加/模拟 Nuxt Auth 库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59608684/