#javascript #reactjs #jestjs #react-testing-library
#javascript #reactjs #jestjs #react-testing-library
Вопрос:
Я застрял в этой библиотеке React-Testing-Library. У меня есть два компонента: HeroesScreen и HeroesDiamondBar, которые отображаются внутри HeroesScreen, когда переменный currentStep становится больше 0. Я хочу имитировать arrowRight в своем тесте, чтобы отображался хотя бы один DiamondBar.
Heroes.jsx:
const HeroesScreen = ({ data, backgroundImage }) => {
const [element, setElement] = useState();
const [currentStep, setCurrentStep] = useState(0);
const screenEl = useRef();
const handler = (e) => {
const nextScreen = e.key === 'PageDown' || e.key === 'ArrowRight';
const prevScreen = e.key === 'PageUp' || e.key === 'ArrowLeft';
if (nextScreen amp;amp; currentStep < LAST_STEP) {
e.stopPropagation();
setCurrentStep(currentStep 1);
} else if (prevScreen amp;amp; currentStep > 0) {
e.stopPropagation();
setCurrentStep(currentStep - 1);
} else {
setCurrentStep(0);
}
};
useEffect(() => {
screenEl.current.focus();
setElement(screenEl.current);
}, []);
useKeys(element, handler);
return (
<div
className="heroes"
style={{ backgroundImage: `url(${backgroundImage})` }}
tabIndex="2"
ref={screenEl}
>
<div className="heroes__cover" data-testid="heroes">
{heroesConfig.map((item, index) => {
const cssIndex = index 1;
const { title, step1, dataId, filterProperty } = item;
return (
<Fragment key={`${title}-${cssIndex}`}>
{currentStep >= step1 amp;amp; (
<HeroesDiamondBar
photo={data[dataId][0].photo}
name={data[dataId][0].name}
points={data[dataId][0][filterProperty]}
cssIndex={cssIndex}
currentStep={currentStep}
{...item}
/>
)}
</Fragment>
);
})}
</div>
</div>
);
};
HeroesScreen.propTypes = {
data: PropTypes.object.isRequired,
backgroundImage: PropTypes.string.isRequired,
};
export default HeroesScreen;
HeroesScreen.test.js:
import React from 'react';
import { render, screen, cleanup } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import HeroesScreen from '@screens/HeroesScreen/HeroesScreen';
import HeroesDiamondBarMock from '@components/HeroesDiamondBar/HeroesDiamondBar';
afterEach(cleanup);
jest.mock('@components/HeroesDiamondBar/HeroesDiamondBar', () => {
let id = 0;
return jest.fn(() => {
return (
<div data-testid={`heroes-diamond-bar-${ id}`}>Heroes Diamond Bar</div>
);
});
});
const props = {
data: {
rare: [
{
name: 'Name 1',
points: '4500',
photo: 'img url',
},
]
},
backgroundImage:
'bg img',
};
describe('<HeroesScreen />', () => {
test('renders a <HeroesDiamondBar /> component with data props', async () => {
const { getAllByTestId, getByTestId } = render(<HeroesScreen {...props} />);
await userEvent.type(getByTestId('heroes'), '{arrowright}');
expect(getAllByTestId(/heroes-diamond-bar/)).not.toBeNull();
});
});
Комментарии:
1. С чем именно вы застряли? Последнее
expect
выдает ошибки? Илиhandler
не вызывается?
Ответ №1:
Решение состоит в том, чтобы перейти data-testid="heroes"
к родительскому div, затем имитация в тестовых работах