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

不想你离开。 提交于 2019-12-05 08:33:56

问题


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


回答1:


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

expect(component.contains(<ComponentName />)).toBe(false)



回答2:


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

expect(wrapper.find('selector').exists()).toBeTruthy()



回答3:


Providing a slightly updated answer based on the documentation for toExist

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();



回答4:


.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.



来源:https://stackoverflow.com/questions/46252396/jest-how-to-test-if-a-component-does-not-exist

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!