vendredi 28 juin 2019

set aria-checked property of radio to true after fireEvent.click in react-testing

I want to set the aria-checked property of radiobutton to true after fireEvent.click. I do not want to do it by setAttribute but onclick.

I have tried the following code to test my component.

Radiobutton.js

function Radiobutton(props) {
  const { label, onClick, onKeyPress, isChecked } = props;

  return (
    <div
      className="radiobutton"
      role="radio"
      onClick={onClick}
      onKeyDown={onKeyPress}
      aria-checked={isChecked}
      tabIndex={0}
      value={label}
    >
      <span className="radiobutton__label">{label}</span>
    </div>
  );
} 

Radiobutton.test.jsx

test("radiobuttons must use click", () => {
  const handleChange = jest.fn();
  const { container } = render(
    <Radiobutton onClick={handleChange} isChecked={false} label="Dummy Radio" />
  );
  const radiobtn = getByRole(container, "radio");
  fireEvent.click(radiobtn);
  expect(handleChange).toHaveBeenCalledTimes(1);
  expect(radiobtn.getAttribute("aria-checked")).toBe("true");

});

I am able to call the handleChange function but unable to change the value of aria-checked. I'm getting the following error.

    expect(received).toBe(expected) // Object.is equality

    Expected: "true"
    Received: "false"

      30 |   expect(handleChange).toHaveBeenCalledTimes(1);
    > 31 |   expect(radiobtn.getAttribute("aria-checked")).toBe("true");
         |                                                 ^
      32 |   console.log(prettyDOM(radiobtn));
      33 | });

      at Object.toBe (src/__tests__/radiobutton.test.jsx:31:49)

I'm new to testing. Any help would be much appreciated. Thanks in advance.

Aucun commentaire:

Enregistrer un commentaire