React测试库-无法找到具有data-testid的元素

我正在关注 react-testing-library 的文档,以查找具有data-testid属性的元素是否已呈现。

react-testing-library 无法找到该元素,即使它存在。

测试

test('Renders step based on the active step', () => {
    render(<RenderStep />, { initialState: { implOnboard: initialState } });
  });
  expect(screen.getByTestId('step-1')).toBeDefined(); //  THROWS ERROR ?
}

成分

 // redux
  const { activeStep } = useSelector((state) => state.implOnboard);

  const renderStep = () => {
    switch (activeStep) {
      case 1:
        console.log('Rendering this '); //  THIS IS GETTING LOGGED TOO!
        return (
          <div>
            <StepOne />
          </div>
        );
      case 2:
        return (
          <div>
            <StepTwo />
          </div>
        );
    }
  };
  return <React.Fragment>{renderStep()}</React.Fragment>;

错误

TestingLibraryElementError: Unable to find an element by: [data-testid="step-1"]

回答

请使用queryByTestId代替getByTestId。它会起作用。


以上是React测试库-无法找到具有data-testid的元素的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>