首页 > 解决方案 > 无法使用 Enzyme find() 找到 DOM 元素

问题描述

我有一个记忆游戏,我想测试单击已转动的存储卡是否显示图像,但我无法使用 Enzyme 获得对元素的引用。让我概述一下用例:

在此处输入图像描述

向用户呈现显示的存储卡图像;

在此处输入图像描述

用户点击下面的蓝色按钮。所有卡片都“转身”并且 onClickhandler 处于活动状态。

此时,当一张卡片被点击时,它被翻转并且图像是可见的。我想为此编写一个测试,并测试是否计算了 2 张相同的卡等。但我无法引用所选卡上的任何道具。

这是我的测试:

   describe("Test the puzzle", () => {
const component = mount(<Board />);
it("should show 1 turned card when clicked", () => {
    const button = component.find(".button");
    const card = component.find(".card");
    const turnedCards = [];

    expect(button).toBeDefined();
    expect(card).toBeDefined();
    act(() => {
        button.props().onClick({});
    });
    card.props().onClick({});
});

});

测试失败并显示消息

 ● Test the puzzle › should show 1 turned card when clicked

Method “props” is meant to be run on 1 node. 0 found instead.

  34 |                      button.props().onClick({});
  35 |              });
> 36 |              card.props().onClick({});                         :13)
     |                   ^                                            7)
  37 |      });
  38 | });                                                            t.js:21856:12)
  39 |                                                                js:929:14)

  at ReactWrapper.single (node_modules/enzyme/src/ReactWrapper.js:1168:13)

“改为找到 0。” 意味着这里没有选择 DOM 元素,即使开发者工具显示了一个 div.class 元素(在这个板上实际上是 36 个)。

在此处输入图像描述

这很奇怪,因为我能够选择按钮 ( const button = component.find(".button");) 并执行

button.props().onClick({});

我在这里想念什么?

"react": "^16.13.1",
"react-dom": "^16.13.1",
"@testing-library/jest-dom": "^5.11.5",
"enzyme": "^3.11.0",
"enzyme-adapter-react-16": "^1.15.5",

标签: javascriptreactjsjestjsenzyme

解决方案


推荐阅读