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'}}>
});
});
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,For more information on testing style of react elements, maybe even using styled components, here is a very informative article by Ilya Zykin.