unit-testing - 使用 Jest 在 Nuxt 中测试组件时如何添加/模拟 Nuxt Auth 库

标签 unit-testing vue.js jestjs nuxt.js

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 的响应方法以便我可以测试我登录/注销的场景?
  • 有没有办法在我的测试中模拟 Nuxt 环境,以便我可以测试我的组件等,就像它们安装在 Nuxt 中一样?这是一个好主意吗?

  • 在此先感谢您的帮助!

    最佳答案

    您可以通过在 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/

    相关文章:

    c++ - 用于非虚拟和私有(private)函数的 Google Mock

    reactjs - 为什么将 Electron 与 SPA 框架结合使用?

    jestjs - 预设 Jest puppeteer 无效

    jestjs - 如何防止 Jest 打印所有跳过的测试?

    unit-testing - GoLang Sarama ConsumerGroup模拟

    .net - 以多线程方式运行 nUnit 测试

    php - 无法下载文件 Symfony 3.4 和 VueJS

    javascript - 从 Flask 网络服务器将全局 JSON 传递给 Vue 应用程序

    unit-testing - 如何在Typeorm中输入事务回调?

    c# - 当参数不完全匹配时模拟成员调用