Skip to content

Instantly share code, notes, and snippets.

@jongan69
Last active January 30, 2023 19:19
Show Gist options
  • Select an option

  • Save jongan69/84d99ab7c7cc062397ab89e53080f339 to your computer and use it in GitHub Desktop.

Select an option

Save jongan69/84d99ab7c7cc062397ab89e53080f339 to your computer and use it in GitHub Desktop.
An example Jest Test for Checkbox With Label

CheckboxWithLabel

CheckboxWithLabel is a React component that allows users to toggle between two labels on a checkbox. It uses the useState hook from React to keep track of the checkbox's state.

Usage

CheckboxWithLabel takes two props - labelOn and labelOff - to set the labels for when the checkbox is checked and unchecked respectively.

<CheckboxWithLabel
  labelOn="On"
  labelOff="Off"
/>

Example

Below is an example of how to use the CheckboxWithLabel component.

import React from 'react';
import CheckboxWithLabel from './CheckboxWithLabel';

function App() {
  return (
    <div>
      <CheckboxWithLabel
        labelOn="On"
        labelOff="Off"
      />
    </div>
  );
}

export default App;

CheckboxWithLabel-test

This renders a checkbox with the label "Off" and when clicked, it will toggle to "On".

import {cleanup, fireEvent, render} from '@testing-library/react';
import CheckboxWithLabel from '../CheckboxWithLabel';
// Note: running cleanup afterEach is done automatically for you in @testing-library/[email protected] or higher
// unmount and cleanup DOM after the test is finished.
afterEach(cleanup);
it('CheckboxWithLabel changes the text after click', () => {
const {queryByLabelText, getByLabelText} = render(
<CheckboxWithLabel labelOn="On" labelOff="Off" />,
);
expect(queryByLabelText(/off/i)).toBeTruthy();
fireEvent.click(getByLabelText(/off/i));
expect(queryByLabelText(/on/i)).toBeTruthy();
});
import {useState} from 'react';
export default function CheckboxWithLabel({labelOn, labelOff}) {
const [isChecked, setIsChecked] = useState(false);
const onChange = () => {
setIsChecked(!isChecked);
};
return (
<label>
<input type="checkbox" checked={isChecked} onChange={onChange} />
{isChecked ? labelOn : labelOff}
</label>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment