如何在使用 Jest 在 Nuxt 中测试组件时添加/模拟 Nuxt 身份验证库



这里的JS新手。

我已经生成了一个Nuxt应用程序,并在我的nuxt.config.js中在全球范围内实现了@nuxt/auth中间件。它在我的应用程序中按预期工作。

现在,我想测试一些引用$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"

很明显,我需要在某处定义身份验证,所以我的问题是:

  1. 我应该在哪里以及如何将此依赖项添加到我的测试中(每个测试?对于所有测试全局?(?
  2. 如何模拟loggedIn方法的响应,以便我可以测试登录/注销的场景?
  3. 有没有办法在我的测试中模拟Nuxt环境,以便我可以测试我的组件等,就好像它们被安装在Nuxt中一样?这甚至是一个好主意吗?

提前感谢任何帮助!

你可以通过在调用 mount 时在选项对象中传递模拟来模拟你的$auth对象

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()
})
})

您可以根据需要扩展模拟,或更改它为每个测试返回的值。

最新更新