Testing an accessible UI

Recently, my team has been writing lots of Cypress tests before releasing a feature. And it struck us that while we were pushing on using testing library for both Cypress and ReactJS, we forgot something, and that is ACCESSIBILITY.

So let me give an example code of a simple UI component:

const TextField = () => (
  <div>
    <label>Foo</label>
    <input type="text" />
  </div> 
);

If we were using Enzyme, the test would be something like this:

it('should display correct value after typing in something', () => {
  const wrapper = shallow(<Textfield />);
  const input = wrapper.find('input');
  input.simulate('change', { target: { value: 'Hello' } });

  expect(input.value).toBe('Hello');
})

Not bad right? It looks okay, but it's not how I see the user will interact with it in the browser, because we are:

  • just finding a random HTML input tag
  • simulating an HTML event
  • checking the property value of an HTML input tag.

Now, maybe I'm just not that familiar on proper use of Enzyme. But once I've used testing-library/react, it changed my way of thinking in testing UI components.

If we were to change the Textfield component and make it more accessible:

const TextField = () => (
  <div>
    <label htmlFor="foo">Foo</label>
    <input id="foo" type="text" />
  </div> 
);

We set a relationship between the label and the input.

Using testing-library/react, we can come up with this test:

it('should display correct value after typing in something', () => {
  // render in browser
  render(<Textfield />);
  // Using the label here as the name of the input field
  const input = screen.getByLabelText('Foo');
  // simulate the user typing 'Bar'
  userEvent.type(input, 'Bar');
  // Check that the input with the label 'Foo' has a value of 'Bar'
  expect(input).toHaveValue('Bar');
  // we can also check if this is really the value displayed in the browser
  expect(screen.getByDisplayValue('Bar')).toBeInTheDocument();
})

We are guided by the guiding principle of Testing Library:

The more your tests resemble the way your software is used, the more confidence they can give you.

In conclusion, by thinking how the user would interact with a UI component in the browser, we can imagine how we would write our tests, at the same time, we can also increase the accessibility of our UI components.

🍻 Cheers and Happy Testing! 🛠️

25