【问题标题】:How to assert on Element 'Array attribute' in Jest/Enzyme?如何在 Jest/Enzyme 中断言元素“数组属性”?
【发布时间】:2018-07-05 15:02:15
【问题描述】:

我的 React 组件有以下呈现的 HTML

<Blueprint2.Select
        disabled={false}
        filterable={false}
        itemRenderer={[Function]}
        items={
          Array [
            "JK",
          ]
        }
        onItemSelect={[MockFunction]}
      >

我要断言的是 items 元素内的数组包含正确的列表,即只是“JK”

我试过了

expect(wrapper.find("Blueprint2.Select").find("[items=['JK']").exists()).toEqual(true);  

但这不起作用。我该如何做这个断言?

更新:事实上,即使只是检查 Blueprint2.Select 的存在也会失败

expect(wrapper.find("Blueprint2.Select").exists()).toEqual(true);  

即使我已经生成了一个快照并且可以在其中看到上面的 HTML。检查具有两部分名称(由点分隔)的元素是否有不同的约定?

【问题讨论】:

    标签: reactjs typescript jestjs enzyme


    【解决方案1】:

    您应该将复杂的语句分解为多个语句,就像在任何其他编程中一样:

    const expectedItems = ["JK",]
    const component = wrapper.find("Blueprint2.Select");
    expect(component.exists()).toBeTruthy();
    

    为数组编写 expect 的关键是要意识到它们是作为 props 传入的。所以你可以直接提取你想要的道具:

    expect(component.props().items).toEqual(expectedItems);
    

    或者,如果您希望获得多个道具的价值:

    expectedProps = {
        items: ['JK',],
        disabled: false,
        filterable: false,
    }
    expect(compoennt.props()).toMatchObject(expectedProps);
    

    【讨论】:

    • 感谢清晰的解释,真的很有帮助。您是否看到我对问题的更新,我似乎无法找到 Blueprint.Select。当我只查找 Select 时,它找到了它,这是酶中的约定吗?
    • 也只是尝试了上面的方法,我得到了错误“[ts] Property 'items' does not exist on type 'HTMLAttributes'”。我需要调整什么才能在打字稿中工作?
    • @NZJames 具体细节取决于Blueprint2.Select的实现。
    猜你喜欢
    • 2017-04-25
    • 2019-05-12
    • 2018-03-28
    • 2020-02-06
    • 2019-09-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多