How to use react-testing-library to test combobox component?
Asked Answered
C

1

6

I'm trying to write more unit tests for my combobox component, but more specifically, I want to simulate keyboard input into the combobox. I've tried using React's testing library's keyboard events (ex: fireEvent.keyDown) but when I debug after firing the event, the input value never changes.

Ideally, I'd like to use React's testing library in my unit tests, but if there's something else that's easier, I'd be open to it.

Basically, all I want to know is: how do I write unit tests for the basic functionalities of my combobox component??

EDIT: now I can't get the unit test to work if I set autoComplete to "off" in the ComboBox props. I've tried keyDown on "A" followed by keyDown on "Enter" and "Tab" but to no avail. Updated code snippet below.

    const dropdownOptions: IComboBoxOption[] = [{ key: "A", text: "A" }, { key: "B", text: "B" }];

    const dropdown = <ComboBox options = { dropdownOptions } autoComplete = { "off" }></ComboBox>

    //in the unit test
    it("Should change input using keyboard events", () => {
            const { getByRole } = render(dropdown);

            const inputNode = getByRole("combobox");
            fireEvent.keyDown(inputNode, { key: "A", code: "KeyA" });
            expect(inputNode.getAttribute("value")).toBe("A");
        })
Continuity answered 9/6, 2020 at 18:36 Comment(2)
Please give a minimal reproducible example.Perchance
@Perchance here's an example! hope it helps explain the situationContinuity
C
3

I believe your code very nearly works as-is. With the following source files, this test passed without issue.

// App.tsx
import React from 'react';
import { Fabric, ComboBox, IComboBoxOption } from 'office-ui-fabric-react';

const dropdownOptions: IComboBoxOption[] = [{ key: "A", text: "A" }, { key: "B", text: "B" }];

function App() {
  return (
    <Fabric><div className="App"><ComboBox options = { dropdownOptions }></ComboBox></div></Fabric>
  );
}

export default App;

// App.test.tsx

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

test('renders learn react link', () => {
  const rendered = render(<App />);
  const combobox = rendered.getByRole("combobox");
  fireEvent.keyDown(combobox, 
    { key: "A", code: "KeyA" }
  );
  expect(combobox.getAttribute("value")).toBe("A");
});
Cromer answered 12/6, 2020 at 0:21 Comment(1)
thanks! looks like KeyPress was the issue in my code. However, I found another issue that's more specific now - could you look at the edit in my original post?Continuity

© 2022 - 2024 — McMap. All rights reserved.