首页 > 解决方案 > 酶 mount().find 没有找到任何东西

问题描述

以下代码:

const wrapper = mount(<Component />);
console.log('how to test this with jest', Object.keys(wrapper.find('h1')));

记录[]所以 find 给了我一个空对象。在浏览器中打开它会显示Component带有内容<h1>hello</h1>

这是错误的选择器h1吗?

文档不包括按标签名称查找元素,但该选择器可以与 JavaScript 中的 querySelector 一起使用。

wrapper.find('.some-class')即使组件返回,尝试也会给我相同的结果<h1 className="some-class">hello</h1>

标签: reactjsenzyme

解决方案


Wrapper.find 返回一个用于测试的 ReactWrapper。

假设您想测试 h1 的存在,您可以这样做:

const wrapper = mount(<Component />);
expect(wrapper.find("h1").exists()).toBe(true);

查看https://enzymejs.github.io/enzyme/docs/api/了解全套 API。


推荐阅读