【问题标题】:Test an whole table React component cells with jest and Enzyme测试整个表格用 jest 和 Enzyme 反应组件单元格
【发布时间】:2020-05-10 00:49:50
【问题描述】:

我正在尝试测试反应组件中的各个行和单元格,组件的“返回”如下所示:

return (
    <div className="app-body">
       <table className="grid">
           <tbody>
               {grid.map((row, rowIdx) => {
                   return <tr className="grid-row" key={rowIdx}>
                       {row.map((node, nodeIdx) => {
                           const { row, col } = node;
                               return <Node
                                   key={nodeIdx}
                                   row={row}
                                   col={col}></Node>
                            })}
                        </tr>
                    })}
                </tbody>
            </table>
        </div>
    );

如何在 jest / Enzyme 中测试每个单元格? 我一直在尝试:

describe('test MyComponent', () => {
    const wrapper = render(<MyComponent />);
    const table = wrapper.find('table');
    const row = render(<tr />)
    const node = render(<Node />);

    it('table grid', () => {
        expect(table).toHaveLength(1);
        expect(row).toHaveLength(1);
        expect(node).toHaveLength(1);
    });
});

为什么它只需要一个节点? 如何收集表中的所有节点?

【问题讨论】:

  • console.log(wrapper.debug()) 的输出是什么?在您的测试中传递给组件的grid 数组的值是什么?
  • 返回 wrapper.debug 不是一个函数。网格起初是空的。它是一个节点对象数组的数组。

标签: reactjs jestjs enzyme


【解决方案1】:

预期为 1,因为只有 1 个 table 元素要查找(对于 expect(table))。对于另外两个(rownode),您只是渲染单个元素(完全独立于您的 MyComponent。如果您要计算 MyComponent 中的表、行和节点的数量,请尝试像这样:

describe('test MyComponent', () => {
    const wrapper = mount(<MyComponent />);
    const table = wrapper.find('table');
    const row = table.find('tr')
    const node = table.find(Node)

    it('table grid', () => {
        expect(table).toHaveLength(1);
        expect(row).toHaveLength(whateverYouExpect);
        expect(node).toHaveLength(whateverYouExpect);
    });
});

【讨论】:

  • 感谢您的帮助!我正在尝试,但它返回两个 0:expect(row).toHaveLength(0);期望(节点).toHaveLength(0);
  • 如果你使用mount而不是render呢?
猜你喜欢
  • 2020-08-27
  • 2018-08-30
  • 2021-01-08
  • 2023-03-27
  • 2018-12-16
  • 2021-06-24
  • 1970-01-01
  • 1970-01-01
  • 2017-02-12
相关资源
最近更新 更多