0

我正在尝试测试 React 组件中给出的按钮数量是否存在。

我试过用谷歌搜索如何回答这个问题,但我没有成功。

我收到以下错误: Unable to find an accessible element with the role "button".

我收到此错误可能是因为代码中没有按钮标签。见下文。

所以,我的问题是,鉴于下面的代码,我如何测试是否呈现了正确数量的按钮?我正在尝试使用 reacts 测试库对此进行测试。谢谢。

以下是相关代码——

 const { alignItems, direction, tab, title, description, buttons, pic } =
    props;
...
 <Grid container spacing={2}>
            {buttons.map((button, i) => (
              // eslint-disable-next-line react/no-array-index-key
              <Grid item key={i}>
                {button}
              </Grid>
            ))}
          </Grid>
...

HomeSection.propTypes = {
  alignItems: PropTypes.string,
  direction: PropTypes.string,
  tab: PropTypes.string,
  title: PropTypes.string.isRequired,
  description: PropTypes.string.isRequired,
  buttons: PropTypes.arrayOf(PropTypes.element).isRequired,
  pic: PropTypes.string.isRequired,
};

这是我编写的当前代码。(这是不正确的,但展示出来可能是件好事。)

 test('checks if it renders the given number of buttons', () => {
         render(<HomeSection
                  title="Topology"
                  description="Math course"
                  buttons={[]}
                  pic="manifold"/>
               );
        screen.debug();
        const items = screen.getByRole('button');
        expect(items).toHaveLength(0);
    });
4

0 回答 0