How to check if an element with certain class name exists using Jest

Let's assume that you have created a component that displays a modal after clicking on a button.

Example:

jsx
import React, { useState } from 'react';

const App = () => {
    
    const [display, setDisplay] = useState(false);
    
    const handleModal = () => {
        
        setDisplay(true);
        
    }
    
    return(
        <div className = 'Block'>
            <button onClick = {handleModal}>Click me</button>
            { display 
            ? <div className = 'Modal'>This is a modal</div> 
            : null
            }
        </div>
    );
    
}

export default App;

If you want to test if a block with a certain class name exists using Jest, you can use the toBeTruthy() function.

Following the previous example:

javascript
import React                              from 'react';
import { render, unmountComponentAtNode } from 'react-dom';
import { act, Simulate }                  from 'react-dom/test-utils';
import { App }                            from '../Components/App';

let container = null;

beforeEach(() => {
    
    container = document.createElement("div");
    document.body.appendChild(container);
    
});

afterEach(() => {
    
    unmountComponentAtNode(container);
    container.remove();
    container = null;
    
});

it('App -> Displays modal on button click', () => {
    
    act(() => {
        
        render(<App/>, container);
        
        Simulate.click(container.querySelector('button'));
        
    });
    
    expect(container.querySelector('.Modal')).toBeTruthy();
    
}

Hi, I'm Erik, an engineer from Barcelona. If you like the post or have any comments, say hi.