React 单元测试报 Unable to find the element with 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 ❌
}

组件

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

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

报错

TestingLibraryElementError: Unable to find an element by: [data-testid="step-1"]
阅读 1.5k
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题