【问题标题】:How to get the root tag name in enzyme?如何获取酶中的根标签名称?
【发布时间】: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


【解决方案1】:

我认为您只是错过了在那里输入的内容。你应该使用.to.equal 而不是toBe

expect(wrapper.first().type()).toEqual('div')

参考: https://airbnb.io/enzyme/docs/api/ShallowWrapper/type.html

附: 这仅在您使用shallow 而不是mount 来渲染组件时才有效。不知道为什么...


更新:

上面的 Matt cmets 举了一个很好的例子。在此处发布以提高知名度:

https://codesandbox.io/s/function-testing-6sxt5

【讨论】:

  • 我在开玩笑,我认为相当于 expect(wrapper.first().type()).toEqual('div') ?我试过了,但得到了与上面相同的结果。也许这是个笑话?
  • 抱歉,已更新为toEqual()。另外,我意识到这适用于shallow,但不适用于mount,不知道为什么......仍在调查。我引用了马特的评论,因为我认为这是一个很好的答案。
  • 如果使用mount,您应该可以使用expect(wrapper.children().type()).toEqual('div')
猜你喜欢
  • 2012-07-04
  • 2014-07-12
  • 2011-11-18
  • 2021-08-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多