Skip to content

Allow screen to use custom queries  #516

@danieljcafonso

Description

@danieljcafonso

Describe the feature you'd like:

Hey everyone 😄
I'd like to when using the screen object to be able to use custom queries previously created with the buildQueries helper.

Suggested implementation:

To avoid potential breaking changes and keeping screen as an object, I'd suggest creating an initializeScreen function that would take a custom queries object as a parameter and return a new screen object.

  • This function would take the current code assigned to the screen object and return a new screen object every time it was called.
  • We could also use it to instantiate the default screen.

Regarding implementation, I'd say it would be like this:

import * as defaultQueries from './queries'

...

export const initializeScreen = customQueries => {
  const queries = {...defaultQueries, ...customQueries}

  return typeof document !== 'undefined' && document.body
    ? getQueriesForElement(document.body, queries, {debug})
    : Object.keys(queries).reduce(
        (helpers, key) => {
          helpers[key] = () => {
            throw new TypeError(
              'For queries bound to document.body a global document has to be available... Learn more: https://testing-library.com/s/screen-global-error',
            )
          }
          return helpers
        },
        {debug},
      )
}

export const screen = initializeScreen()

Teachability, Documentation, Adoption, Migration Strategy:

  1. The users can import the initializeScreen on some test-utils file they may have.
  2. They call the function with their custom queries and obtain a new screen object that references it
  3. They can re-export that screen as the default one and use it on their tests.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions