在另一个计算属性上调用 getter 不是测试中的函数

ami*_*aro 1 vue.js jestjs vuex

我一直在尝试模拟 getter 函数,但该函数也被另一个计算属性调用,并且它作为未定义函数返回。

这是一个面包屑组件,会根据路由路径而变化。第一个测试正常通过,因为该组件不应该渲染。但第二个测试尝试使用用户名通过 getter 获取用户数据。

我的疑问是关于模拟吸气剂。它不是应该返回 beforeEach 定义的模拟对象吗?

提前致谢!

这是测试规范:

import {
  shallowMount,
  createLocalVue
} from '@vue/test-utils'
import Breadcrumb from '@/components/Breadcrumb.vue'
import Vuex from 'vuex'
import VueRouter from 'vue-router'

const localVue = createLocalVue()

localVue.use(Vuex)
localVue.use(VueRouter)
const router = new VueRouter()

describe('Breadcrumb.vue', () => {
  let store

  beforeEach(() => {
    store = new Vuex.Store({
      getters: {
        getUserByUsername: (path) => ({
          name: {
            first: 'FirstName',
            last: 'LastName'
          }
        })
      }
    })
  })

  it('renders home page breadcrumb', () => {
    const wrapper = shallowMount(Breadcrumb, { store, router, localVue })
    const component = wrapper.find('.breadcrumb')
    expect(component.text()).toBe('')
  })
  it('renders users page breadcrumb', () => {
    router.push('/users')
    const wrapper = shallowMount(Breadcrumb, { store, router, localVue })
    const component = wrapper.find('.breadcrumb')
    expect(component.text()).toBe('')
  })
})
Run Code Online (Sandbox Code Playgroud)

第一个测试通过,但第二个测试返回:

TypeError: this.getUserByUsername is not a function

  41 |       crumbs.push(this.users)
  42 |       for (const path of paths) {
> 43 |         const user = this.getUserByUsername(path)
     | ^
  44 |         if (user) {
  45 |           crumbs.push({
  46 |             label: `${user.name.first} ${user.name.last}`,
Run Code Online (Sandbox Code Playgroud)

这是该组件的计算函数:

  computed: {
    ...mapGetters(['getUserByUsername']),
    breadcrumbs () {
      const crumbs = []
      const routePath = this.$route.path
      if (routePath === '/' || routePath === '/404') return []
      const paths = routePath.split('/')
      delete paths[0]
      crumbs.push(this.home)
      crumbs.push(this.users)
      for (const path of paths) {
        const user = this.getUserByUsername(path)
        if (user) {
          crumbs.push({
            label: `${user.name.first} ${user.name.last}`,
            path: `/${path}`
          })
        }
      }

      return crumbs
    }
  }
Run Code Online (Sandbox Code Playgroud)

ski*_*tle 5

我怀疑你需要改变这一点:

getUserByUsername: (path) => ({
Run Code Online (Sandbox Code Playgroud)

到:

getUserByUsername: () => (path) => ({
Run Code Online (Sandbox Code Playgroud)

从错误消息和组件代码来看,真实版本似乎getUserByUsername正在返回一个函数,因此模拟版本需要执行相同的操作。查看原件getUserByUsername以确认。

回想一下,getter 的外部函数不是您显式调用的。当您访问该属性时,它在幕后使用,并state作为其第一个参数传递。