Dom-testing-library: Add getByDescriptionTerm

Created on 26 Oct 2018  路  3Comments  路  Source: testing-library/dom-testing-library

Hey @kentcdodds,

I'm totally enjoying using dom- and react-testing-library - thanks a lot!

Describe the feature you'd like:

We're using HTML description lists in our application:

<dl>
  <dt>term1</dt>
  <dd>value1</dd>
  <dt>term2</dt>
  <dd>value2</dd>
</dl>

I think it might be handy to select a dd element by its dt. In React for example, it could be used like this:

const { getByDescriptionTerm } = render(<MyDescriptionList />);
const dd = getByDescriptionTerm("term1");

Suggested implementation:

Tbh, I haven't yet looked into the internals of dom-testing-library. I suppose, it wouldn't be too different from other existing selectors. One thing that might be tricky though is that dt doesn't necessarily contain a string but might also wrap other DOM elements.

Describe alternatives you've considered:

So far, I'm just asserting that all dt and dd elements exist and have the expected content. I haven't figured out a good way to match dt and dd elements to each other in my tests though.

I'm curious to hear what you think about the idea and its feasibility!

Best,
Nicolas

Most helpful comment

I wanted to comment on this and possibly provide an alternative in case anyone else wants to tests definition lists - which may not be very common but are very useful.

You can use the getByRole to get the dt or dd but you might need to stick on an aria-label attribute and give it a value to use, i.e.

<dl>
  <dt aria-label="term1">term1</dt>
  <dd>value1</dd>
  <dt aria-label="term2">term2</dt>
  <dd>value2</dd>
</dl>

in RTL you can then use the below and assert as necessary

it("Display term", () => {
    expect(screen.getByRole("term", { name: "term1" }))
});

All 3 comments

Thanks i did try it

Hi @nicolasschabram,

I think that tags like dl, dt, and dd are implementation details. Unless I'm mistake, the same could be accomplished via divs and spans and the user doesn't care either way.

In addition I literally had never heard of these tags until just now and had to look up on MDN to see what they even are. I don't think that they're used enough to justify the extra code. You could however create your own queries for your application if you have need of this frequently.

I hope that's helpful. Good luck!

I wanted to comment on this and possibly provide an alternative in case anyone else wants to tests definition lists - which may not be very common but are very useful.

You can use the getByRole to get the dt or dd but you might need to stick on an aria-label attribute and give it a value to use, i.e.

<dl>
  <dt aria-label="term1">term1</dt>
  <dd>value1</dd>
  <dt aria-label="term2">term2</dt>
  <dd>value2</dd>
</dl>

in RTL you can then use the below and assert as necessary

it("Display term", () => {
    expect(screen.getByRole("term", { name: "term1" }))
});
Was this page helpful?
0 / 5 - 0 ratings