muestra.js
const Sample = () => { const [show, setShow] = useState(false); const onShow = () => { setShow(!show); } return( <div> <button onClick={onShow}>{show ? 'Hide Text' : 'Show text'}</button> {show && <label>Welcome!!</label>} </div> ); }; export default Sample;Muestra.prueba.js
import Sample from '../components/sample'; import React from "react"; test('render Sample text matcher', () => { render(<Sample />); const titleElement = screen.getByText(/Welcome!!/) expect(titleElement).toBeInTheDocument; })Lanza el siguiente error. ¿Cómo puedo escribir testcase si el elemento se representa con valor de estado?
TestingLibraryElementError: Unable to find an element with the text: /Welcome!!/. This could be because the text is broken up by multiple elements. In this case, you can provide a function for your text matcher to make your matcher more flexible.Como solución alternativa, justo después de renderizar, puede intentar hacer clic en el botón que activa su pantalla:
document.querySelector('button').click();Primero debe hacer clic en su botón. De lo contrario show es falso y el texto no se muestra.
Puedes usar:
const button = screen.getByRole('button'); fireEvent.click(button); // import this from react-testing-library