我按照 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"]