【发布时间】:2019-11-29 22:46:31
【问题描述】:
我正在尝试测试其输出取决于属性的组件,即: props.editable == 'true' : 渲染输入否则渲染 div
我已经尝试过:
expect(wrapper.first().type()).toBe('div')
但我得到 [Function: ComponentName]
这是我的代码:
组件文件.js
function ComponentName(props) {
if (props.editable) return <input />
else return <div />
}
ComponentFile.test.js
it('should render a div if not editable', () => {
const wrapper = mount(<ComponentName editable={false} />
expect(wrapper.first().type()).toBe('div')
})
上述测试失败,因为它得到 [Function: ComponentName] 我也尝试过 wrapper.getElement().type 但它也是一个函数。
我能够通过这样做暂时得到我想要的结果:
expect(wrapper.html().substr(0, 4)).toBe('<div')
但我希望有一种更惯用的方式
编辑: 解决了。 Turns out it works if you use shallow instead of mount.
【问题讨论】:
-
测试
ComponentName的更好方法:codesandbox.io/s/function-testing-6sxt5(检查ComponentName内的__tests__文件夹并运行“测试”选项卡)。我还建议通过添加唯一的 className 或 id 来更具体地使用 div 元素。然后你可以将你的断言简化为:expect(wrapper.find('div.someUniqueClassName').exists()).toBeTruthy()
标签: reactjs unit-testing tags jestjs enzyme