Languages

React - onChange event doesn't work for checkbox with fireEvent in @testing-library/react

1 points
Asked by:
Greg
1505

I am writing tests for my React application and IĀ got some problem. My checkbox does not change checked property state when IĀ fire fireEvent.change(input!, {target: {checked: true}}) method. I useĀ rebass library. Below IĀ attach more details.

React component:

import React, { useState } from 'react';
import { Text} from 'rebass';
import { Label, Checkbox } from '@rebass/forms';
// some code here...

const RegisterForm = () => {
  const [agreement, setAgreement] = useState(false);

  // some code here...

  return (
    // some code here...
    <Label>
      <Checkbox
          name="agreement"
          checked={agreement}
          onChange={e => setAgreement(e.target.checked)}
      />
      I have read and agreed...
    </Label>
    {!agreement && <Text id="message">Agreement was not given!</Text>}
    // some code here...
  );
};

export default RegisterForm;

Test:

import React from 'react';
import RegisterForm from '../registerForm';
import { render, act, fireEvent } from '@testing-library/react';

test('Agreement test', () => {
  const register = render(<RegisterForm />);

  const input = register.querySelector<HTMLInputElement>('[name="agreement"]');
  act(() => {
    fireEvent.change(input!, { target: { checked: true } });
  });

  const message = register.querySelector<HTMLElement>('[id="message"]');
  expect(message).toBeNull();
});
1 answers
4 points
Answered by:
Greg
1505

Try to useĀ fireEvent.click(...) instead ofĀ fireEvent.change(...).

Example:

import React from 'react';
import RegisterForm from '../registerForm';
import { render, act, fireEvent } from '@testing-library/react';

test('Agreement test', () => {
  const register = render(<RegisterForm />);

  const input = register.querySelector<HTMLInputElement>('[name="agreement"]');
  act(() => {
    // fix:
    fireEvent.click(input!, { target: { checked: true } });
  });

  const message = register.querySelector<HTMLElement>('[id="message"]');
  expect(message).toBeNull();
});
1 comments
Greg
I found dome discussion about the problem: https://github.com/testing-library/react-testing-library/issues/156
Add comment
Hey šŸ‘‹
Would you like to know what we do?
  • Dirask is a friendly IT community for learners, professionals and hobbyists to share their knowledge and help each other in extraordinary easy way.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.