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.
show
isfalse
, so of course the label isn't getting rendered. You need to click the button to toggle it.