【问题标题】:Enzyme: How to test interactions on shallow component酶:如何测试浅层成分的相互作用
【发布时间】:2018-11-04 01:25:18
【问题描述】:

我想测试一些与我的列表组件的基本 UI 交互。

我想测试给定的“全选”复选框是否有效,使用 Enzyme+Jest 和浅根对象。

事先,我确认没有选择任何内容。这确实很好用:

const allBox = list.find('Checkbox.select-all')
expect(allBox.prop('checked')).toBe(false)
mainRows.find('Checkbox').forEach( (node) => {
    expect(node.prop('checked')).toBe(false)
})

但我无法在该主复选框上触发“点击”(或“更改”)……

allBox.simulate('click')`

我怀疑,因为 Checkbox 仍然是肤浅的 <Checkbox> 而不是真正的 html 风格的 <input type='checkbox'…>

但是我能做什么呢?

安装(实际渲染)整个列表组件将变得非常庞大。我可以以某种方式安装(相当小的)复选框子组件,然后触发它的事件吗?和/或我需要.dive()吗?

expect()ing 之前还有什么其他东西现在都被选中了吗?

各种<Checkbox>checked 属性与组件状态相关联。那我需要list.instance().update()吗?甚至.forceUpdate()? → 有some discussion on the Enzyme tracker,关于.update() 是否/如何工作……

无论如何,我运气不好

Expected value to be:       true
Received:                   false

  180 |         allBox.simulate('change')
  181 |         list.instance().forceUpdate()
  182 | 
> 183 |         expect(allBox.prop('checked')).toBe(true)
  184 |         // verify, that did the job:
  185 |         mainRows.find('Checkbox').forEach( (node) => {
  186 |             expect(node.prop('checked')).toBe(true)

【问题讨论】:

  • 这对我有用:在simulate 调用之后再次查询该选择器。像这样:expect(list.find('.select-all').prop('checked')).toBe(true).
  • 你能分享你浅渲染组件的代码吗?它是否管理复选框的状态?

标签: javascript testing jestjs enzyme


【解决方案1】:

“改变”,而不是“点击”

嗯,首先,我必须模拟“变化”,而不是“点击”。由于<Checkbox> 组件的所有肤浅性只有一个 onChange 处理程序。 (只有当它变成实际的 html 时,点击才会导致改变……sinca 就是 <input type="checkbox…> 所做的)


现在进入核心问题:

list.find('.list-bottombar').find('Checkbox.select-all').debug()

<Checkbox className="select-all" checked={false}…

让我们触发更改:

list.find('.list-bottombar').find('Checkbox.select-all').simulate('change')

我们做得好吗?

list.find('.list-bottombar').find('Checkbox.select-all').debug()

是的!

<Checkbox className="select-all" checked={true}…

使用速记会显示相同的内容吗?

bottomBar.find('Checkbox.select-all').debug()

<Checkbox className="select-all" checked={false}…

不!所以@konekoya 是对的,你必须通过 find 继续检索,不允许之前的速记。 (嗯。哈。这是文档中的任何地方吗?!?)


[强制]更新有帮助吗? (剧透:没有。)

bottomBar.update()

Error: ShallowWrapper::update() can only be called on the root

好的,那么

list.update() bottomBar.find('Checkbox.select-all').debug()

<Checkbox className="select-all" checked={false}…

运气不好。

list.instance().update() TypeError: list.instance(...).update 不是函数 list.instance().forceUpdate() bottomBar.find('Checkbox.select-all').debug()

<Checkbox className="select-all" checked={false}…

(虽然该框仍然被选中,如上长查询仍然验证)

潜水也无济于事。

tl;博士;旧列表的任何快捷方式都只是过时数据的快捷方式。必须一次又一次地从根元素find()


附: Enzyme 的知情人士quite explicitly confirms this

当您在 v2 中使用 .find 时,您会得到一个自动更新的包装器 当根包装器更新时。在 v3 中,它是不可变的,所以你必须 从根重新查找以查看反映的更改。

【讨论】:

    猜你喜欢
    • 2018-02-09
    • 2020-08-26
    • 1970-01-01
    • 2019-02-16
    • 2021-06-04
    • 1970-01-01
    • 2020-03-08
    • 2018-03-10
    • 1970-01-01
    相关资源
    最近更新 更多