Jest - 如何测试组件是否不存在?

时间:2017-09-16 09:36:32

标签: jestjs enzyme

如何检查某个组件是否不存在,即某个特定组件是否尚未呈现?

6 个答案:

答案 0 :(得分:24)

您可以使用酶contains来检查组件是否已呈现:

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

答案 1 :(得分:18)

.contains接收React Node或节点数组作为参数。相反,请使用.find

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

答案 2 :(得分:6)

如果您使用的是 react-testing-library(我知道 OP 不是,但我通过网络搜索发现了这个问题),那么这将起作用:

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

您可以按 TextRole 和其他几个查询。有关详细信息,请参阅 docs

注意: queryBy* 如果未找到,将返回 null。如果您使用 getBy* 那么它会因为找不到元素而出错。

答案 3 :(得分:3)

根据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 :(得分:2)

.contains不希望选择器,与find不同。您可以查看ShallowWrapper的length属性

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

我发现我需要将此语法与Enzyme和Jest一起使用,以测试渲染输出中是否存在连接的组件。

答案 5 :(得分:0)

我们使用 Jest 和 Enzyme,我发现唯一好的测试是导入子组件并以这种方式测试:

expect(component.find(SubComponent).length).toEqual(0); // or (1) for exists, obvs

我尝试了所有其他答案,但没有一个可靠地工作。

相关问题