#reactjs #testing
#reactjs #тестирование
Вопрос:
У меня проблема в том, что я не могу протестировать текст, который обернул функцию в toggle.
Как я смотрю на это, функция fireEvent.click выполнена хорошо. Итак, текст «Когда вечеринка начинается» был отрисован. Я проверил screen.debug().
Но значение hiddenMessage равно нулю. Итак, мне не удалось протестировать «ожидать (hiddenMessage …….»
test('just console.log', () => {
const { getByText, queryByText } = render(<Guide />);
const titleOfGuide = getByText(/the party/); >>>> visible text
const hiddenMessage = queryByText(/^When the party starts/). >> When toggle is on, visible text
fireEvent.click(titleOfGuide)
screen.debug(); >>>> the result I want to render. Hidden text is visible !
console.log(hiddenMessage);>>>> hiddenMessage is a null. Why is null?..
// expect(hiddenMessage).toBeTruthy();
}).
ниже приведен код для тестирования
const Guide = () => {
const [toggle, setActiveToggle] = useState([false, false,false, false, false]);
const activeToggle = useCallback((menu) => () => {
setActiveToggle((prevState) => {
const newState = [...prevState];
newState[menu] = !newState[menu];
return newState;
});
}, [toggle]);
return (
// ... The toggle contol function in here. (activeToggle)
<ListColumn>
<div>
the party
</div>
{toggle[0] amp;amp; (
<div>
When the party starts
</div>
)}
</ListColumn>
// ... Other ListColumn component ...
)
}
Комментарии:
1. Можете ли вы опубликовать код, который вы собираетесь протестировать?
Ответ №1:
Кажется, вы нажали щелчок после queryByText
скрытого текста. Попробуйте выполнить before, а затем выполнить запрос.
test('just console.log', () => {
const { getByText, queryByText } = render(<Guide />);
const titleOfGuide = getByText(/the party/); >>>> visible text
fireEvent.click(titleOfGuide)
const hiddenMessage = queryByText(/^When the party starts/). >> When toggle is on, visible text
screen.debug(); >>>> the result I want to render. Hidden text is visible !
console.log(hiddenMessage);>>>> hiddenMessage is a null. Why is null?..
// expect(hiddenMessage).toBeTruthy();
}).
Комментарии:
1. Извините, я закодировал ваше решение «expect(hiddenMessage).toBeTruthy();» //// но hiddenMessage имеет нулевое значение, мой тест не прошел.
2. @devsner, вы эмулируете щелчок по titleOfGuide, но я не вижу никакого атрибута onClick для этого в коде. Вы уверены, что скрытый текст отображается при нажатии на этот div?