在 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/