首页 > 解决方案 > 点击【React】后测试组件中的每个按钮是否被禁用

问题描述

我有一个组件,它映射一些方向并<button>为每个方向呈现一个。单击按钮时,它被禁用。

我必须设置一个测试来确定单击后按钮是否被禁用。

我的组件:

 <div>
                    {sortDirections.map((sortDirection) => (
                      <button
                        key={sortDirection}
                        disabled={
                          sortFilters.direction === sortDirection &&
                          sortFilters.payType === sortVariant.payType
                        }
                        className="btn"
                        onClick={() =>
                          handleSortFilters({
                            payType: sortVariant.payType,
                            direction: sortDirection,
                          })
                        }
                      >
                        {sortDirection}
                      </button>
                    ))}
                  </div>

到目前为止,我将提供我的测试,但它确实有错误

 it('Sort button should be disabled on click', () => {
    render(
      <ProductSorter
        sortFilters={sortFilters}
        handleSortFilters={handleSortFilters}
      />
    );
    expect(screen.getAllByRole('button')).toHaveLength(4);

    // ERROR: Argument of type 'HTMLElement[]' is not assignable to parameter of type 'Element | Node | Document | Window'.
    fireEvent.click(screen.getAllByRole('button'));
  });

我可以成功测试一个按钮,但由于它是一组按钮而苦苦挣扎,我需要测试每个按钮。想知道我是否必须单独编写带有特定测试的每个按钮?

标签: reactjsjestjsreact-testing-library

解决方案


您应该能够在数组上使用 forEach 循环:

it('Sort button should be disabled on click', () => {
    render(
      <ProductSorter
        sortFilters={sortFilters}
        handleSortFilters={handleSortFilters}
      />
    );
    const buttons = screen.getAllByRole('button')
    buttons.forEach((x)=>expect(x).toHaveProperty('disabled'))
  });

推荐阅读