-1

sample.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;

Sample.test.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;
})

It throw following error. How can I write testcase if element render with state value?

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.
1
  • The initial state of show is false, so of course the label isn't getting rendered. You need to click the button to toggle it.
    – jonrsharpe
    Commented Nov 30, 2021 at 11:48

2 Answers 2

1

You need to click on your button first. Otherwise show is false and the text is not displayed.

You can use:

const button = screen.getByRole('button');
fireEvent.click(button); // import this from react-testing-library
1

As a workaround, just after rendering you could try to do a click on the button that activate your display :

document.querySelector('button').click();
1
  • How Can I use it using JEST? Commented Nov 30, 2021 at 12:13

Not the answer you're looking for? Browse other questions tagged or ask your own question.