【发布时间】:2019-06-11 20:30:57
【问题描述】:
在 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. Render function should return a single root node.
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 mounting 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'
}
}
}
});
那么如何测试一个返回多个根节点的功能组件呢?
【问题讨论】:
-
你使用什么构建工具?
-
只是为了其他人,他们想知道是否可以从渲染函数返回多个
VNode[]- 这是不可能的,render函数的签名只允许一个VNode,而不是多个。
标签: javascript unit-testing vue.js