Skip to content

Improve a11y aspect of the code #2208

@crs1138

Description

@crs1138

I'm following up the conversation from Telegram channel. It'd be great to improve the overall a11y standards within the lessons and exercises.

Here are my notes so far.


Part 5.c Testing React Apps

About finding elements

This chapter seems like a missed opportunity to introduce the students to a11y. Each input should have a corresponding <label> element and the tests should taken an advantage of the getByLabelText() function. Tests written this way will reinforce the effort to implement code with focus on accessibility.

No, not really. It's just the way it's being taught is not leading to good practice in terms of a11y and in terms of reasons for the test. Let's start with the a11y. In terms of accessibility, it is insufficient to rely on placeholders, they might not be read. Each should have a corresponding element (this can be visually hidden if the design requires that, but for now let's assume no such design requirement exists). User interacts with such a form made out of various input boxes in a way that, they'll look for a label where to fill in a value. The JSX could be something like the following code:

The test would specify the required input with something like this:

const username = screen.getByLabelText(/username/i)
const password = screen.getByLabelText(/password/i)
const loginBtn = screen.getByRole('button', {name: /login/i, exact: false})

This coerces the developer to write the React code that has a11y already in mind. Notice that not only there will need to be a element for each of the input boxes, but we are testing for the label text using the regex without paying attention to the letter case or whether it has or hasn't got the colon after the text. The code passing the test will then look for example as follows:

return (
    <form onSubmit={...}>
        <div>
            <label htmlFor="username">Username: </label>
            <input type="text" id="username" value={...} onChange={...} placeholder="[email protected]" />
        </div>
        <div>
            <label htmlFor="password">Password: </label>
            <input type="password" id="password" value={...} onChange={...} />
        </div>
        <button type="submit">Login</button>
    </form>
  )

Testing this way is more future proof, because this way of finding element will still be valid if the designer comes next week and says, I don't want visible labels and btw, change the placeholder to match a username syntax like this.

Metadata

Metadata

Assignees

No one assigned

    Labels

    accessibilitygeneralIssue or pull request that is not specific to any particular part of the course material

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions