Skip to content

Throw an error if getBy* queries return anything other than one result. #202

Closed
@kentcdodds

Description

@kentcdodds

Describe the feature you'd like:

As a random thought, what if we throw an error if you use getBy* query and there's more than 1 element that could be returned for the given query? We already do that if there are no elements returned.

I'm not certain how I feel about it, but it seems like a good idea. I had the idea when responding to #201

As it occurs to me, one very common mistake when using CodeSandbox is people render the thing they're testing in the document as well as run tests with it. The problem is that CodeSandbox does not isolate the tests' DOM from the app's DOM, so you often wind up interacting with the element that's rendered in the app rather than the one you're testing. Sometimes it happens to work, but much of the time it doesn't. If we implemented this, then people would get an error and it may help them know why.

Suggested implementation:

Take this:

https://github.com/kentcdodds/dom-testing-library/blob/369d17e169e5c7f47688482b8f0ad8ecda2ee35f/src/query-helpers.js#L32-L36

Change it to:

function resultOrNull(queryFunction, ...args) {
  const result = queryFunction(...args)
  if (result.length === 1) return result[0]
  return null
}

Describe alternatives you've considered:

Currently we allow this:

// Given: <div>Hello</div><div>Hello2</div>
getByText(/.*hello.*/i) // what should this return?

Right now we'll get the first, but that could be undesirable and even surprising.

Teachability, Documentation, Adoption, Migration Strategy:

This would require a breaking change, some slight changes to the docs, and the error message could help with teachability. As for migration, hopefully most people only have one result already, if they don't it may be a little surprise but should hopefully be pretty easy to fix by either improving the TextMatch to only match one element, or switching to the getAllBy* version of the query and grabbing the first result.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions