酶联包装器的containsAllMatchingElements无法找到元素

时间:2018-10-05 10:22:46

标签: reactjs enzyme

我正在尝试测试Menu是否呈现为MenuItems

import React from "react";
import { configure } from "enzyme";
import Adapter from "enzyme-adapter-react-16";

import { mount } from "enzyme";
configure({ adapter: new Adapter() });

const MenuItem = ({ children }) => <li>{children}</li>;
const Menu = () => (
  <ul>
    <MenuItem>foo</MenuItem>
    <MenuItem>bar</MenuItem>
  </ul>
);

const HyperMenu = () => <Menu />;

const wrapper = mount(<HyperMenu />);

expect(wrapper.containsAllMatchingElements([<MenuItem />])).toBeTruthy();

尽管看起来像a valid case,但酶找不到任何MenuItems,并且测试失败。这是为什么?

codesandbox

wrapper.debug()吐口水

<HyperMenu>
  <Menu>
    <ul>
      <MenuItem>
        <li>
          foo
        </li>
      </MenuItem>
      <MenuItem>
        <li>
          bar
        </li>
      </MenuItem>
    </ul>
  </Menu>
</HyperMenu> 

1 个答案:

答案 0 :(得分:2)

containsAllMatchingElements的工作方式是确定“包装器中的某个元素看起来是否像”,通过检查“预期元素的所有道具”是否存在来传递这些元素。

文档底部列出的“常见陷阱”之一是“请记住,该方法也基于节点子节点的匹配来确定匹配”。

看一下源代码,比较是通过函数internalNodeCompare完成的,该函数将道具here和子项here进行比较。

containsAllMatchingElements以上的测试中,通过了<MenuItem />,这导致它寻找没有道具且没有子代的MenuItem,这是因为测试中的两个MenuItem元素失败了包装器都有孩子。

如果测试被修改为包含MenuItem个子代,则测试通过:

expect(wrapper.containsAllMatchingElements([<MenuItem>foo</MenuItem>, <MenuItem>bar</MenuItem>])).toBeTruthy();   // SUCCESS