如何使用react renderer在jest中测试JSX元素数组

时间:2018-01-03 11:42:22

标签: reactjs jsx jestjs

我正在使用React 16.2,并希望测试我的组件功能 当调用其中一个函数时,它会返回一个带按钮的元素数组,这些元素有一个我想测试的onClick道具。

问题是,我只能找到数组中的第一个元素。

代码如下:

Comp.js

class Comp extends Component {

    renderButtons = () => {
        const list = [];

        list.push(<Button key="first" onClick={() => console.log('foo')}/>);
        list.push(<Button key="second" onClick={() => console.log('bar')}/>);
        list.push(<Button key="third" onClick={() => console.log('baz')}/>);

        return list;
    }

    render() {
        return (
            <div>Empty div</div>
        )
    }
}

Comp.test.js

test('.renderButtons', () => {
    const comp = new Comp();
    const component = renderer.create(comp.renderButtons());

    const root = components.root;

    // Using root.findByProps({key: 'second'}); throws an error
});

技术堆栈:

  • React 16.2.0
  • Jest 21.2.1
  • React-test-renderer: 16.2.0

1 个答案:

答案 0 :(得分:0)

这是一个较旧的问题,但似乎有很多意见,所以我将添加一个答案。

“ key”道具(以及“ ref”道具)是保留的React道具,如果访问它会抛出错误。在findByProps函数中可以使用任何其他道具。 Test Instance上有其他功能,例如findAllByType。

这里是一个例子:

const SimpleComponent = ({text}) => (<div>{text}</div>);

const ListComponent = () => {
  const list = [];
  list.push(<SimpleComponent key="first" text="the first one" />);
  list.push(<SimpleComponent key="second" text="the second one" />);
  list.push(<SimpleComponent key="third" text="the third one"/>);
  return list;
}

test('ListComponent renders correctly', () => {
  const component = renderer.create(<ListComponent/>);

  const list = component.root.findAllByType(SimpleComponent);
  expect(list.length).toBe(3);
  expect(list[1].props.text).toBe('the second one');

  const third = component.root.findByProps({text: 'the third one'});
  expect(third.type).toBe(SimpleComponent);
});