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

Joe*_*dee 31 jestjs enzyme

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

小智 31

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

expect(wrapper.find('selector').exists()).toBeTruthy()
Run Code Online (Sandbox Code Playgroud)


And*_*rle 29

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

expect(component.contains(<ComponentName />)).toBe(false)
Run Code Online (Sandbox Code Playgroud)

  • 在我的例子中,`contains`调用总是返回`false`.我使用`expect(component.find('ComponentName').exists()).toBeFalsy();`而不是像Periback所建议的那样. (9认同)
  • @shinyatk我相信`find`和`exists`是重要的部分。toBe(false)应该可以正常工作。如果您使用[jest-酶匹配器](https://github.com/FormidableLabs/enzyme-matchers/tree/master/packages/jest-enzyme#tocontainmatchingelement),则也可以只写`expect(component.find(' ComponentName'))。toExist()` (2认同)

Sne*_*kse 8

根据酶匹配器的文档toExist提供稍微更新的答案。这将要求您安装该enzyme-matchers软件包。

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();
Run Code Online (Sandbox Code Playgroud)

  • 这需要 `enzyme-matchers` 这个库。https://github.com/FormidableLabs/enzyme-matchers (4认同)

Bra*_*ing 6

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

expect(component.queryByText("Text I care about")).not.toBeInTheDocument();
Run Code Online (Sandbox Code Playgroud)

您可以通过查询TextRole和其他几个人。有关更多信息,请参阅文档

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


Mar*_*rom 5

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

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

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