将测试用例从 Enzyme 迁移到 RTL

问题描述 投票:0回答:1

我们正在将应用程序升级到 React 18,并且需要将我们的 tet 从 Enzyme 迁移到 RTL。我正在努力寻找一个好的解决方案来重写我的测试:

function useButtonTests(
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  comp: React.ReactComponentElement<any, any>,
  buttonId: string,
) {
  const component = shallow(comp);
  const match = component.findWhere((node) => node.prop('id') === buttonId);
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  let result: any;
  if (match .length > 1) {
    result = expect(match.findWhere((node) => node.type() === 'button'));
  } else {
    result = expect(match);
  }
}

我似乎不知道如何重写上面的代码片段,尤其是带有谓词函数的部分component.findWhere((node) => ...

我感谢任何意见。预先感谢

reactjs typescript enzyme react-testing-library
1个回答
0
投票
import { render } from '@testing-library/react';

function useButtonTests(
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  comp: React.ReactElement<any>,
  buttonId: string,
) {
  // Render the React component
  const { getByTestId, getAllByTestId, getByRole } = render(comp);

  // Find elements matching the provided button ID
  const match = getByTestId(buttonId);

  // Initialize result variable
  let result: any;

  // Check if multiple matches are found
  if (Array.isArray(match) && match.length > 1) {
    // If multiple matches, assert each match to be a button element
    result = getAllByTestId(buttonId).map((element) => expect(element.tagName).toBe('BUTTON'));
  } else {
    // If single match, assert it to exist
    result = expect(getByTestId(buttonId)).toBeInTheDocument();
  }
}

// Test Case
test('useButtonTests - Button Identification', () => {
  // Test data
  const component = <YourComponentNameHere />; // Replace with your actual component
  const buttonId = 'yourButtonId'; // Replace with your actual button ID

  // Execute the test
  useButtonTests(component, buttonId);

  // Assert the expected result
  // Replace the below line with appropriate assertion based on your test case
  // For example: expect(result.toBeInTheDocument(); // This asserts the element to be in the document
});

© www.soinside.com 2019 - 2024. All rights reserved.