首页 > 解决方案 > 为什么酶“安装”包装只是呈现

问题描述

我现在正在学习测试并创建了一个非常简单的示例。在我要测试的组件中,我在一个标签li内呈现了一些元素。ul

当我将组件包装在mount包装器中并打印html到控制台时,我得到了<ul></ul>

我不知道为什么?现在的问题当然是我找不到任何button我想模拟点击的元素。

它与我如何呈现待办事项列表有关吗?酶不能与 renderFunction 一起使用吗?

这是示例:https ://codesandbox.io/s/v8ljxo5xn5

对应的文件是TodoBody.jsTodoBody.test.js

谢谢!

标签: javascriptreactjsjestjsenzyme

解决方案


这是因为 todos 数组是空的,所以 map 没有返回任何内容(可能是 [] - 你需要检查一下)。快速解决方案:

describe("the todobody component", () => {
      test("it should call the passed in onDelete func from props", () => {
        const todos = ['test'];
        const test = { onDelete: () => {} };
        jest.spyOn(test, "onDelete");
        const wrapper = mount(<TodoBody onDelete={test.onDelete} todos={todos} />);

        // this just renders <ul></ul> why??

        console.log(wrapper.html());
      });
    });


const renderTodos = () => {
    return todos.map(todo => (
      <li key={`${todo}`}>
        <p>{todo}</p>
        <button onClick={handleDelete} data-test="test-btn-delete">
          X
        </button>
      </li>
    ));
  };

安慰:

<ul><li><p>test</p><button data-test="test-btn-delete">X</button></li></ul> 

推荐阅读