小智 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)
根据酶匹配器的文档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)
如果您使用的是react-testing-library(我知道 OP 不是,但我通过网络搜索发现了这个问题),那么这将起作用:
expect(component.queryByText("Text I care about")).not.toBeInTheDocument();
Run Code Online (Sandbox Code Playgroud)
您可以通过查询Text
,Role
和其他几个人。有关更多信息,请参阅文档。
注意: 如果没有找到queryBy*
将返回null
。如果您使用,getBy*
那么它会因找不到元素而出错。
.contains
与 find 不同,不需要选择器。可以查看ShallowWrapper的length属性
expect(wrapper.find('...')).toHaveLength(0)
我发现我需要将此语法与 Enzyme 和 Jest 一起使用来测试渲染输出中是否存在连接组件。