javascript - 如何使用返回任何元素数组的渲染函数对 Vue.js 功能组件进行单元测试?

标签 javascript unit-testing vue.js

在 Vue.js 中,功能组件可以通过使用 render 函数返回多个根节点 returns an array of createdElements .

export default {
  functional: true,
  props: ['cellData'],
  render: function (h, context) {
    return [
      h('td', context.props.cellData.category),
      h('td', context.props.cellData.description)
    ]
  }
}

这很好用,但我在尝试为此类组件创建单元测试时遇到了问题。在组件上使用 shallowMount 会导致 [Vue warn]: Multiple root nodes returned from render function。渲染函数应返回单个根节点。

import { shallowMount } from '@vue/test-utils'
import Cell from '@/components/Cell'

wrapper = shallowMount(Cell, {
  context: {
    props: {
      cellData {
        category: 'foo',
        description: 'bar'
      }
    }
  }
});

This github issue建议组件需要包装在单个根节点中才能实际呈现它,但尝试这样做会导致 [vue-test-utils]: mount.context can only be used when mount a functional component

import { shallowMount } from '@vue/test-utils'
import Cell from '@/components/Cell'

wrapper = shallowMount('<div><Cell></div>', {
  context: {
    props: {
      cellData {
        category: 'foo',
        description: 'bar'
      }
    }
  }
});

那么如何测试返回多个根节点的功能组件呢?

最佳答案

您可以使用 v-bind="$attrs" [1]v-on="$listeners" [2] 。然后你可以使用 propsData 将 Prop 传递给包装器组件..

import { mount } from '@vue/test-utils'
import Cell from '@/components/Cell'

const WrappedCell = {
  components: { Cell },
  template: `
    <div>
      <Cell v-bind="$attrs" v-on="$listeners" />
    </div>
  `
}

const wrapper = mount(WrappedCell, {
  propsData: {
    cellData: {
      category: 'foo',
      description: 'bar'
    }
  }
});

关于javascript - 如何使用返回任何元素数组的渲染函数对 Vue.js 功能组件进行单元测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54239343/

相关文章:

javascript - 在 javascript/typescript/nodejs 中创建可能的组合

javascript - Ajax、JSON 对象与 php 交互

unit-testing - 带模拟的测试套件。无法使用struct方法

PHPUnit 找不到异常类

javascript - SonarQube 和 Karma 代码覆盖率 - 未解析的文件路径

vue.js - 在不重新安装组件的情况下更新 Vue Router?

php - Laravel 8 Jetstream Inertia 所有 Inertia 请求都必须收到有效的 Inertia 响应

javascript - 回显日期的引用错误

javascript 在 textarea onload 中选择文本

javascript - 在 vue.js 中按类型对评论进行排序