Search code examples
reactjsjestjsenzyme

Test whole table React component cells with Enzyme


I'm trying to test individual rows and cells in a react component, the "return" of the component looks like:

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>
    );

how can I test each cell in jest / Enzyme ? I've been trying:

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);
    });
});

why it expecting only ONE node ? how can I collect all nodes in a table ?


Solution

  • It is expecting 1 because there is only 1 table element to find (for the expect(table)). For the other two (row and node), you are just rendering single elements (completely independent of your MyComponent. If you are trying to count the number of tables, rows, and Nodes in MyComponent, try something like this:

    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);
        });
    });