Home > Software engineering >  How to write unit testcase using JEST if text shown conditionally with useState
How to write unit testcase using JEST if text shown conditionally with useState

Time:11-30

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.

CodePudding user response:

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

document.querySelector('button').click();

CodePudding user response:

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
  • Related