Vue Test Utils Axios Mock-TypeError:无法读取未定义的属性“状态” UI行为测试失败

问题描述

UI行为

当单击验证帐户按钮后API调用失败时,如果错误为404,则显示b-警报,并显示消息“在数据库中找不到该用户”,但是如果错误为500,则消息为“错误服务器。请稍后再试。”

error

测试失败

我正在尝试使用 Jest vue test utils 中模拟axios调用,但是当axios调用引发错误时出现此错误

error-api

我想获取错误状态代码以在b-警报组件中显示特定消息。因此,我编写了此方法

async sendVerificationCode(token) {
      try {
        const url = `${process.env.API_AUTH}/account/user-validation`
        this.showSpinner = true
        const { data } = await this.$axios.$post(url,{
          headers: {
            Authorization: token
          }
        })
        this.sentPhone = `******${data.lastDigits}`
        this.showSpinner = false
        this.statusCode = 200
        this.$bvModal.show('verifyAccountModal')
      } catch (e) {
        this.showSpinner = false
        this.statusCode = e.response.status
        if (this.statusCode === 404) {
          this.showMessage(true,'Cannot find that user in the database')
        } else {
          this.showMessage(true,'Error in the server. Try again later')
        }
      }
}

我写的测试是:

import axios from 'axios'
import Vuex from 'vuex'
import flushPromises from 'flush-promises'
import BootstrapVue,{ BAlert } from 'bootstrap-vue'
import { mount,createLocalVue } from '@vue/test-utils'
import Profile from '@/pages/perfil.vue'

jest.mock('axios',() => ({
    post: () => {},}))

const localVue = createLocalVue()
localVue.use(Vuex)
localVue.use(BootstrapVue)

describe('API Calls',() => {

    let state
    let store

    beforeEach(() => {
        state = {
            isAccountsverificationFeatureEnabled: true
        }

        store = new Vuex.Store({
            modules: {
                flags: {
                    state
                }
            }
        })
    })

    it('if click on verify account button and status code is 404,it should show an alert with an account verification error',async () => {
        const wrapper = mount(Profile,{ store,localVue })
        wrapper.setData({ isOwner: undefined,isLessee: undefined })
        await flushPromises()
        wrapper.find('.verify-account-button')
        await wrapper.vm.sendVerificationCode('Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9iOiJIUzI1NiIsInR5cCI6IkpXVCJ')
        wrapper.setData({ isError: true,statusCode: 404,errorMessage: 'Cannot find that user in the database.' })
        await flushPromises()
        const errorAlert = wrapper.findComponent(BAlert)
        errorAlert.trigger('show')
        expect(errorAlert.text()).toBe('Cannot find that user in the database.')
    })

})

谢谢。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)