如何测试nuxt.js asyncData和获取挂钩

问题描述

我一直在尝试使用nuxt的文件(asyncData和fetch钩子)进行测试,我在测试vue.js正常生命周期时没有问题,但是我注意到vue / test-utils并未给出关于如何使用的明确说明测试nuxt的钩子。

login.vue

asyncData() {
 const email = localStorage.getItem("email") || ""
 const password = localStorage.getItem("password") || ""
 return { email,password }
},mounted() {
 this.setMaxStep()
}

signup.vue

async fetch({ store,redirect,query }) {
  const res = await store.dispatch("getSavedFormData")
  if (res) {
    store.dispatch("setNotification",{
      message: "PrevIoUs application is loaded"
    })
  }
},

尝试如下进行测试,但是我没有运气(也尝试过其他各种方法,但是我不知道从哪里寻找信息)


import {
  shallowMount,config
} from "@vue/test-utils"
import Login from "../../../pages/login

describe("Login",() => {

  let wrapper

  beforeEach(() => {
    wrapper = shallowMount(Login)
  })

  it("gets asyncData",async () => {
    await wrapper.vm.asyncData
  })
})

解决方法

迟到的答案,但我希望这对这个问题的新手有所帮助。

当我遇到这个问题时,我做了什么来解决这个问题,只是在安装(或浅安装)组件时添加了 data() 方法:

// import shallowMount & component/page to be tested

const wrapper = shallowMount(Component,{
   data() {
      // assuming username data is the data needed by component
      username: 'john.doe'
   }
})

由于 asyncData() 在服务器上运行,我们的测试失败了,因为 asyncData() 从未运行,因此从未获得预期的数据。

因此,使用 data() 方法提供客户端数据是有意义的,以便组件/页面在运行测试时拥有必要的数据。

, 如果您只想使用模拟数据测试组件的行为,

Gyen Abubakar's answer 可以是一个解决方案。但请记住,asyncData 和 fetch 钩子未经过测试,您可能需要对其进行测试以获得更好的单元测试。

如果你想测试你的 asyncData 和 fetch hook,你需要在挂载组件后添加:

  1. 异步数据

    wrapper = shallowMount(Login);
    wrapper.setData({
      ...(await wrapper.vm.$options.asyncData({ store })) // add more context here
    });
    
  2. 获取钩子

    wrapper = shallowMount(Login);
    await Login.fetch.call(wrapper.vm); // using `call` to inject `this`