·
I was doing unit testing on a form that triggers validation styling on the blur event (when losing focus).
So I did a POC.
Here is the code of the form:
import { useState } from "react"; import './App.css'; function App() { const [show, setShow] = useState(false); return ( <div className="App"> <header className="App-header"> <input type="text" name='a' data-testid="hpi-a" onBlur={()=>setShow(!show)}/> <input type="text" name='b' data-testid="hpi-b" /> {show?<p name='c' data-testid="hpi-c">Blur from a to be done</p>:null} </header> </div> ); } export default App;
You see that there are two inputs of type text.
The input text with the name 'a' triggers the displaying of the conditional block named 'c' when we blur from it (lose of focus for getting to the next input).
And here is the related unit test:
import { render, screen, fireEvent } from '@testing-library/react'; import App from './App'; test('paragraph c should be in document', async () => { render(<App />); fireEvent.blur(screen.getByTestId('hpi-a')) expect(screen.getByTestId('hpi-c')).toBeInTheDocument(); }); test('paragraph c should not be in document', async () => { render(<App />); const submitButton = screen.queryByTestId('hpi-c'); expect(submitButton).toBeNull() // it doesn't exist });
We render the component.
Then we fire a blur.
And we check the result: when we blur, the conditional block is displayed else nothing appears.