Jest - how to test if a component does not exist?

后端 未结 5 2002
离开以前
离开以前 2021-02-04 23:15

How do I check if a component is not present, i.e. that a specific component has not been rendered?

相关标签:
5条回答
  • 2021-02-04 23:57

    You can use enzymes contains to check if the component was rendered:

    expect(component.contains(<ComponentName />)).toBe(false)
    
    0 讨论(0)
  • 2021-02-05 00:00

    .contains receives a React Node or array of Nodes as an argument. Instead, use .find:

    expect(wrapper.find('selector').exists()).toBeTruthy()
    
    0 讨论(0)
  • 2021-02-05 00:02

    .contains does not expect a selector, unlike find. You can look at the length attribute of the ShallowWrapper

    expect(wrapper.find('...')).toHaveLength(0)

    I found I needed to use this syntax with Enzyme and Jest to test if a Connected Component existed in the rendered output.

    0 讨论(0)
  • 2021-02-05 00:12

    Providing a slightly updated answer based on the documentation for enzyme-matchers's toExist. This will require you to install the enzyme-matchers package.

    function Fixture() {
      return (
        <div>
          <span className="foo" />
          <span className="bar baz" />
        </div>
      );
    }
    
    const wrapper = mount(<Fixture />); // mount/render/shallow when applicable
    
    expect(wrapper.find('span')).toExist();
    expect(wrapper.find('ul')).not.toExist();
    
    0 讨论(0)
  • 2021-02-05 00:13

    If you're using react-testing-library (I know the OP wasn't but I found this question via web search) then this will work:

    expect(component.queryByText("Text I care about")).not.toBeInTheDocument();
    

    You can query by Text, Role, and several others. See docs for more info.

    Note: queryBy* will return null if it is not found. If you use getBy* then it will error out for elements not found.

    0 讨论(0)
提交回复
热议问题