【问题标题】:How to add/mock the Nuxt Auth library when testing components in Nuxt with Jest使用 Jest 在 Nuxt 中测试组件时如何添加/模拟 Nuxt Auth 库
【发布时间】:2020-04-23 19:04:56
【问题描述】:

这里是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 中一样?这是个好主意吗?

提前感谢您的帮助!

【问题讨论】:

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


    【解决方案1】:

    您可以通过在调用mount 时将模拟传递给options 对象来模拟您的$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()
      })
    })
    

    您可以随意扩展模拟,或更改它为每个测试返回的值。

    【讨论】:

      猜你喜欢
      • 2021-03-17
      • 2019-05-21
      • 2021-12-30
      • 2020-12-16
      • 2021-09-14
      • 2021-07-11
      • 1970-01-01
      • 2020-05-05
      • 2019-02-28
      相关资源
      最近更新 更多