简体   繁体   English

如何用工厂函数组织Vue单元测试?

[英]How to organize Vue unit test with factory functions?

I'm trying to write unit tests for my Dashboard.vue component using factory functions so that I could overwrite the store and wrapper as per needed.我正在尝试使用工厂函数为我的Dashboard.vue组件编写单元测试,以便我可以根据需要覆盖storewrapper

Here is the code这是代码

import { mount, createLocalVue } from '@vue/test-utils'
import mergeWith from 'lodash.mergewith'
import mutationobserver from 'mutationobserver-shim'
import Vuex from 'vuex'
import BootstrapVue from 'bootstrap-vue'
import Dashboard from '@/views/dashboard/Dashboard'
import { FontAwesomeIcon } from '@fortawesome/vue-fontawesome'
import { library as faLibrary } from '@fortawesome/fontawesome-svg-core'
import { faUser, faThumbsUp, faSignOutAlt, faBorderAll, faAlignJustify, faTrashAlt, faRandom } from '@fortawesome/free-solid-svg-icons'
import flushPromises from 'flush-promises'

jest.mock('@/services/app.service.js')

faLibrary.add(faUser, faThumbsUp, faSignOutAlt, faBorderAll, faAlignJustify, faTrashAlt, faRandom)

const localVue = createLocalVue()
localVue.use(Vuex)
localVue.use(BootstrapVue)
localVue.use(mutationobserver) // This is a necessary polyfill for Bootstrap-Vue
localVue.component('font-awesome-icon', FontAwesomeIcon)

function customizer (ovjValue, srcValue) {
  /*
      If the property that takes precedence is an array,
      overwrite the value rather than merging the arrays
    */
  if (Array.isArray(srcValue)) {
    return srcValue
  }
  /*
      If the property that takes precedence is an empty object,
      overwrite the property with an empty object
     */
  if (srcValue instanceof Object && Object.keys(srcValue).length === 0) {
    return srcValue
  }
}

describe('DashBoard component tests', () => {
  let state
  // let actions
  // let getters
  let store
  let wrapper

  let dashBoardData = [
    { db_name: 'Jobs', dxp_dashboardref: 1, dxp_hidden: 0, dxp_position: 1, dxp_ref: 926 },
    { db_name: 'Firms', dxp_dashboardref: 2, dxp_hidden: 0, dxp_position: 2, dxp_ref: 927 },
    { db_name: 'CRM', dxp_dashboardref: 5, dxp_hidden: 0, dxp_position: 3, dxp_ref: 987 }
  ]

  // beforeEach(() => {
  state = {
    auth: {
      user: {
        auids: '',
        md_clock: 0,
        md_picture: '',
        ps_fname1: '',
        ps_surname: '',
        psname: 'Test Test',
        psref: 0
      }
    },
    app: {
      dashBoardData: []
    }
  }

  function createStore (overrides) {
    const defaultStoreConfig = {
      // state: {
      //   state
      // },
      getters: {
        getDashBoardData: () => dashBoardData
      },
      actions: {
        loadDashboard: jest.fn(),
        updateDashBoardData: jest.fn()
      }
    }
    return new Vuex.Store(
      state,
      mergeWith(defaultStoreConfig, overrides, customizer)
    )
  }

  function createWrapper (overrrides) {
    const defaultMountingOptions = {
      localVue,
      store: createStore()
    }
    return mount(
      Dashboard,
      mergeWith(
        defaultMountingOptions,
        overrrides,
        customizer)
    )
  }

  // START: Testing existence of DOM Elements tests
  it('is a Vue instance', () => {
    const wrapper = createWrapper({})
    expect(wrapper.isVueInstance).toBeTruthy()
  })
})

Essentially, I'm trying to use a createWrapper method which has a default store unless overrides or customizer are passed.本质上,我正在尝试使用具有默认存储的createWrapper方法,除非通过overridescustomizer程序。 When I run the test I get the following errors当我运行测试时,出现以下错误

console.error node_modules/vuex/dist/vuex.common.js:899 console.error node_modules/vuex/dist/vuex.common.js:899

[vuex] unknown getter: getDashBoardData [vuex] 未知获取器:getDashBoardData

console.error node_modules/vue/dist/vue.runtime.common.dev.js:621 console.error node_modules/vue/dist/vue.runtime.common.dev.js:621

[Vue warn]: Error in render: "TypeError: Cannot read property 'length' of undefined" [Vue 警告]:渲染错误:“TypeError:无法读取未定义的属性‘长度’”

Now, I have two questions:现在,我有两个问题:

  1. Why am I being thrown unknown getter when I have declared it in the defaultStoreConfig ?当我在defaultStoreConfig中声明它时,为什么会抛出unknown getter
  2. The second error comes from the state .第二个错误来自state For some reason it doesn't recognize the state variable I'm passing.由于某种原因,它无法识别我传递的 state 变量。 Any ideas why?任何想法为什么?

If I simply declare the wrapper inside a beforeEach like so I can pass some of my test but for others which I need to overwrite either getters or actions , I'm not able to do that unless I have the factory functions如果我只是在beforeEach中声明包装器,这样我就可以通过一些测试,但对于其他需要覆盖gettersactions的测试,除非我有工厂函数,否则我无法做到这一点

    getters = {
      getDashBoardData: () => dashBoardData
   },
    actions = {
    loadDashboard: jest.fn(),
    updateDashBoardData: jest.fn()
  }

  store = new Vuex.Store({
    state,
    actions,
    getters
  })
  })

Any help will be highly appreciated!任何帮助将不胜感激!

Solved this by passing the state inside defaultStoreConfig rather than separately when creating the store通过在defaultStoreConfig中传递 state 解决了这个问题,而不是在创建商店时单独传递

Code:代码:

    const defaultStoreConfig = {
      state: {
        auth: {
          user: {
            auids: '',
            md_clock: 0,
            md_picture: '',
            ps_fname1: '',
            ps_surname: '',
            psname: 'Test Test',
            psref: 0
          }
        },
        app: {
          dashBoardData: []
        }
      },
      getters: {
        getDashBoardData: () => dashBoardData
      },
      actions: {
        loadDashboard: jest.fn(),
        updateDashBoardData: jest.fn()
      }
    }

Test:测试:

  it('is a Vue instance', () => {
    const wrapper = createWrapper()
    expect(wrapper.isVueInstance).toBeTruthy()
  })

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM