使用酶在 .map 函数中测试 JSX

IT技术 javascript reactjs mocha.js enzyme
2021-05-09 03:50:28

所以说我有这张桌子:

 <table>
  <thead>
    <tr>
      <th>cat name</th>
    </tr>
  </thead>
  <tbody>
    {cats.map(cat => {
      return (
        <tr key={cat.id}>
          <td styleName="table-item">{ cat.name }</td>
        </tr>
      );
    })}
  </tbody>
</table>

我如何使用酶测试 map 函数中的 jsx?

我能够很好地测试它的其他部分,如下所示:

describe('<CatsTable />', () => {
  const wrapper = mount(
    <CatsTable cats={cats} />
  );

  it('renders correctly', () => {
    expect(wrapper.find('table')).to.have.length(1);
    expect(wrapper.find('tbody')).to.have.length(1);
  });
});

但是如果我用 map 函数里面的东西尝试同样的事情,它会返回 undefined

1个回答

可以使用下面的代码来测试map函数里面的表的其他部分

describe('<CatsTable />', () => {
  const wrapper = mount(
    <CatsTable cats={cats} />
  );

  it('renders child correctly', () => {
      expect(wrapper.find('tbody').children()).to.have.length(cats.length);
      expect(wrapper.find('tbody').children().find('tr')).to.have.length(cats.length);

  });

您可以在此处的文档中阅读有关如何使用酶的更多信息http://airbnb.io/enzyme/docs/api/