Having the following component:
import { useState } from 'react';
export function MyComponent() {
const [val, setVal] = useState(false);
return (
<div>
big container
<button onClick={() => setVal(!val)}>click</button>
{val && <div>small container</div>}
</div>
);
}
export default MyComponent;
There is a div containing the text "small container", which only appears when val is true.
I want to write a test in jest for this but don't know how to mock the value of val there
Here is my code so far:
it('small container visible only when val is true', () => {
const { queryByText } = render(<MyComponent />);
const toTest = queryByText('small container');
expect(toTest).not.toBeInTheDocument();
});
this test passes, but how can be added val set to true in order to test that toTest is present in the document?
You can click the button which will set the val to true.
it('small container visible only when val is true', () => {
const {queryByText, getByTestId} = render(<MyComponent />);
const clickButton = getByTestId('your.button.test.id');
fireEvent.click(clickButton);
expect(queryByText('small container')).toBeInDocument();
});
React testing library does not recommend to test implementation details as per documented here. That's why you might not want to access internal state of component while testing.