How to test the style of a div within a React component

912 Views Asked by At

I have a toggle button that shows and hides a div in my component. Rather new to testing and not sure how to test the toggle. Essentially when studentDisplay is false I have a style that sets the display of a div to none. When studentDisplay is true the style is set to display block. Any suggestions and or ideas would be greatly appreciated.

Method in component I would like to test

import React, {useState} from 'react';

export default function App() {
const [studentDisplay, setStudentDisplay] = useState(false);

function handleStudentDisplay() {
 setStudentDisplay(!studentDisplay);
}

return (
  <div className="App">
   <button onClick={handleStudentDisplay}>
      <span>Student Name</span>
   </button>

   <div style={studentDisplay ? {display:'block'} : {display:'none'}}>
    Student 
   </div>
  </div>
 );
}

Test example

import React from 'react';
import renderer from 'react-test-renderer';
import { render, fireEvent, act } from '@testing-library/react';

describe('Student Toggle', () => {
  it('should display student', () => {
    const eventHandler = jest.fn();
    const { getByRole } = render(<button onClick={eventHandler}/>);

    act(() => {
     const button = getByRole('button');
     fireEvent.click(button);
    });

    expect(eventHandler).toHaveBeenCalled();
    //how do I test? <div style={studentDisplay ? {display:'block'} : {display:'none'}}>
  });
});
1

There are 1 best solutions below

0
On

You can use expect from RTL. Here is an example to test the display property of an element, you can add a className or fetch using id or element,

const TargetElement = document.getElementsByClassName('button-class-name');
const style = window.getComputedStyle(TargetElement[0]);

expect(style.display).toBe('none');
expect(style.display).toBe('block');

For more information on testing style of react elements, maybe even using styled components, here is a very informative article by Ilya Zykin.