我正在关注 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 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"]
答案 0 :(得分:3)
对于案例,请使用 queryByTestId
代替 getByTestId
。它会起作用。