【问题标题】:wrapper.find with id in enzyme and jest doesn't find elementwrapper.find with id in酵素和jest没有找到元素
【发布时间】:2019-12-19 20:50:52
【问题描述】:

我是 Jest 和 Enzyme 测试的新手,我想知道为什么 find 函数不适用于 id。

//来自react的html,就是id增量在哪里的代码

<div className="App-body">
  <div className="changePage">
    <button className="Selections" onClick={this.decrementPage}>Previous</button>
    <p className="changePageNumber">{this.state.page}</p>
    <button className="Selections" id="increment" onClick={this.incrementPage}>Next</button>
  </div>
</div>

//测试

it('next page', () => {
  const wrapper = shallow(<Home />)
  const incrementPage = wrapper.find('#increment')
  incrementPage.simulate('click')
  const countState = wrapper.state().page
  expect(countState).toEqual(2)
})
Method “simulate” is meant to be run on 1 node. 0 found instead.

25 |   //const text = wrapper.find('p').text()
 26 |   const incrementPage = wrapper.find('#increment')
> 27|   incrementPage.simulate('click')
    |                 ^                   

【问题讨论】:

  • 当我遇到 find 与元素不匹配的问题时,我会使用诸如 console.log(wrapper.debug()) 之类的东西来准确查看 Enzyme 安装了什么以及它正在做什么。它可能会给你一些线索。如果不是,也许将其输出添加到您的问题中。
  • 除了console.log之外,webstorm和visual studio代码让你调试npm测试设置断点和检查变量内容,在调试控制台中使用不同的查找组合等。设置适当的调试环境可能会有所帮助。

标签: reactjs jestjs enzyme


【解决方案1】:

尝试使用mount 而不是shallowshallow 不会渲染超出第一级元素。在您的情况下,仅呈现具有 className 'App-Body' 的 div

【讨论】:

  • 我也有同样的问题,谢谢,现在我知道了 shalow 和 mount 的区别
  • 问题是读取我的 if 而我想读取我的 else,有什么想法吗?
  • 是的,我知道,但是如果你有并且如果在返回中,应该如何选择一个或另一个?
  • 那么这应该是你测试的一部分。 if(condition_not_met) { // incrementPage 应该是未定义的 }
猜你喜欢
  • 2021-07-06
  • 2023-04-10
  • 2020-08-12
  • 1970-01-01
  • 2020-07-24
  • 2021-06-22
  • 2021-02-12
  • 2018-12-16
  • 2019-08-30
相关资源
最近更新 更多