๐Ÿ Simple and complete React DOM testing utilities that encourage good testing practices.

Overview

React Testing Library

goat

Simple and complete React DOM testing utilities that encourage good testing practices.


Read The Docs | Edit the docs



Build Status Code Coverage version downloads MIT License All Contributors PRs Welcome Code of Conduct Discord

Watch on GitHub Star on GitHub Tweet

Table of Contents

The problem

You want to write maintainable tests for your React components. As a part of this goal, you want your tests to avoid including implementation details of your components and rather focus on making your tests give you the confidence for which they are intended. As part of this, you want your testbase to be maintainable in the long run so refactors of your components (changes to implementation but not functionality) don't break your tests and slow you and your team down.

The solution

The React Testing Library is a very lightweight solution for testing React components. It provides light utility functions on top of react-dom and react-dom/test-utils, in a way that encourages better testing practices. Its primary guiding principle is:

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

Installation

This module is distributed via npm which is bundled with node and should be installed as one of your project's devDependencies:

npm install --save-dev @testing-library/react

or

for installation via yarn

yarn add --dev @testing-library/react

This library has peerDependencies listings for react and react-dom.

You may also be interested in installing @testing-library/jest-dom so you can use the custom jest matchers.

Docs

Suppressing unnecessary warnings on React DOM 16.8

There is a known compatibility issue with React DOM 16.8 where you will see the following warning:

Warning: An update to ComponentName inside a test was not wrapped in act(...).

If you cannot upgrade to React DOM 16.9, you may suppress the warnings by adding the following snippet to your test configuration (learn more):

// this is just a little hack to silence a warning that we'll get until we
// upgrade to 16.9. See also: https://github.com/facebook/react/pull/14853
const originalError = console.error
beforeAll(() => {
  console.error = (...args) => {
    if (/Warning.*not wrapped in act/.test(args[0])) {
      return
    }
    originalError.call(console, ...args)
  }
})

afterAll(() => {
  console.error = originalError
})

Examples

Basic Example

// hidden-message.js
import * as React from 'react'

// NOTE: React Testing Library works well with React Hooks and classes.
// Your tests will be the same regardless of how you write your components.
function HiddenMessage({children}) {
  const [showMessage, setShowMessage] = React.useState(false)
  return (
    <div>
      <label htmlFor="toggle">Show Message</label>
      <input
        id="toggle"
        type="checkbox"
        onChange={e => setShowMessage(e.target.checked)}
        checked={showMessage}
      />
      {showMessage ? children : null}
    </div>
  )
}

export default HiddenMessage
// __tests__/hidden-message.js
// these imports are something you'd normally configure Jest to import for you
// automatically. Learn more in the setup docs: https://testing-library.com/docs/react-testing-library/setup#cleanup
import '@testing-library/jest-dom'
// NOTE: jest-dom adds handy assertions to Jest and is recommended, but not required

import * as React from 'react'
import {render, fireEvent, screen} from '@testing-library/react'
import HiddenMessage from '../hidden-message'

test('shows the children when the checkbox is checked', () => {
  const testMessage = 'Test Message'
  render(<HiddenMessage>{testMessage}</HiddenMessage>)

  // query* functions will return the element or null if it cannot be found
  // get* functions will return the element or throw an error if it cannot be found
  expect(screen.queryByText(testMessage)).toBeNull()

  // the queries can accept a regex to make your selectors more resilient to content tweaks and changes.
  fireEvent.click(screen.getByLabelText(/show/i))

  // .toBeInTheDocument() is an assertion that comes from jest-dom
  // otherwise you could use .toBeDefined()
  expect(screen.getByText(testMessage)).toBeInTheDocument()
})

Complex Example

// login.js
import * as React from 'react'

function Login() {
  const [state, setState] = React.useReducer((s, a) => ({...s, ...a}), {
    resolved: false,
    loading: false,
    error: null,
  })

  function handleSubmit(event) {
    event.preventDefault()
    const {usernameInput, passwordInput} = event.target.elements

    setState({loading: true, resolved: false, error: null})

    window
      .fetch('/api/login', {
        method: 'POST',
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify({
          username: usernameInput.value,
          password: passwordInput.value,
        }),
      })
      .then(r => r.json().then(data => (r.ok ? data : Promise.reject(data))))
      .then(
        user => {
          setState({loading: false, resolved: true, error: null})
          window.localStorage.setItem('token', user.token)
        },
        error => {
          setState({loading: false, resolved: false, error: error.message})
        },
      )
  }

  return (
    <div>
      <form onSubmit={handleSubmit}>
        <div>
          <label htmlFor="usernameInput">Username</label>
          <input id="usernameInput" />
        </div>
        <div>
          <label htmlFor="passwordInput">Password</label>
          <input id="passwordInput" type="password" />
        </div>
        <button type="submit">Submit{state.loading ? '...' : null}</button>
      </form>
      {state.error ? <div role="alert">{state.error}</div> : null}
      {state.resolved ? (
        <div role="alert">Congrats! You're signed in!</div>
      ) : null}
    </div>
  )
}

export default Login
// __tests__/login.js
// again, these first two imports are something you'd normally handle in
// your testing framework configuration rather than importing them in every file.
import '@testing-library/jest-dom'
import * as React from 'react'
// import API mocking utilities from Mock Service Worker.
import {rest} from 'msw'
import {setupServer} from 'msw/node'
// import testing utilities
import {render, fireEvent, screen} from '@testing-library/react'
import Login from '../login'

const fakeUserResponse = {token: 'fake_user_token'}
const server = setupServer(
  rest.post('/api/login', (req, res, ctx) => {
    return res(ctx.json(fakeUserResponse))
  }),
)

beforeAll(() => server.listen())
afterEach(() => {
  server.resetHandlers()
  window.localStorage.removeItem('token')
})
afterAll(() => server.close())

test('allows the user to login successfully', async () => {
  render(<Login />)

  // fill out the form
  fireEvent.change(screen.getByLabelText(/username/i), {
    target: {value: 'chuck'},
  })
  fireEvent.change(screen.getByLabelText(/password/i), {
    target: {value: 'norris'},
  })

  fireEvent.click(screen.getByText(/submit/i))

  // just like a manual tester, we'll instruct our test to wait for the alert
  // to show up before continuing with our assertions.
  const alert = await screen.findByRole('alert')

  // .toHaveTextContent() comes from jest-dom's assertions
  // otherwise you could use expect(alert.textContent).toMatch(/congrats/i)
  // but jest-dom will give you better error messages which is why it's recommended
  expect(alert).toHaveTextContent(/congrats/i)
  expect(window.localStorage.getItem('token')).toEqual(fakeUserResponse.token)
})

test('handles server exceptions', async () => {
  // mock the server error response for this test suite only.
  server.use(
    rest.post('/api/login', (req, res, ctx) => {
      return res(ctx.status(500), ctx.json({message: 'Internal server error'}))
    }),
  )

  render(<Login />)

  // fill out the form
  fireEvent.change(screen.getByLabelText(/username/i), {
    target: {value: 'chuck'},
  })
  fireEvent.change(screen.getByLabelText(/password/i), {
    target: {value: 'norris'},
  })

  fireEvent.click(screen.getByText(/submit/i))

  // wait for the error message
  const alert = await screen.findByRole('alert')

  expect(alert).toHaveTextContent(/internal server error/i)
  expect(window.localStorage.getItem('token')).toBeNull()
})

We recommend using Mock Service Worker library to declaratively mock API communication in your tests instead of stubbing window.fetch, or relying on third-party adapters.

More Examples

We're in the process of moving examples to the docs site

You'll find runnable examples of testing with different libraries in the react-testing-library-examples codesandbox. Some included are:

You can also find React Testing Library examples at react-testing-examples.com.

Hooks

If you are interested in testing a custom hook, check out React Hooks Testing Library.

NOTE: it is not recommended to test single-use custom hooks in isolation from the components where it's being used. It's better to test the component that's using the hook rather than the hook itself. The React Hooks Testing Library is intended to be used for reusable hooks/libraries.

Guiding Principles

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

We try to only expose methods and utilities that encourage you to write tests that closely resemble how your React components are used.

Utilities are included in this project based on the following guiding principles:

  1. If it relates to rendering components, it deals with DOM nodes rather than component instances, nor should it encourage dealing with component instances.
  2. It should be generally useful for testing individual React components or full React applications. While this library is focused on react-dom, utilities could be included even if they don't directly relate to react-dom.
  3. Utility implementations and APIs should be simple and flexible.

Most importantly, we want React Testing Library to be pretty light-weight, simple, and easy to understand.

Docs

Read The Docs | Edit the docs

Issues

Looking to contribute? Look for the Good First Issue label.

๐Ÿ› Bugs

Please file an issue for bugs, missing documentation, or unexpected behavior.

See Bugs

๐Ÿ’ก Feature Requests

Please file an issue to suggest new features. Vote on feature requests by adding a ๐Ÿ‘ . This helps maintainers prioritize what to work on.

See Feature Requests

โ“ Questions

For questions related to using the library, please visit a support community instead of filing an issue on GitHub.

Contributors

Thanks goes to these people (emoji key):


Kent C. Dodds

๐Ÿ’ป ๐Ÿ“– ๐Ÿš‡ โš ๏ธ

Ryan Castner

๐Ÿ“–

Daniel Sandiego

๐Ÿ’ป

Paweล‚ Mikoล‚ajczyk

๐Ÿ’ป

Alejandro ร‘รกรฑez Ortiz

๐Ÿ“–

Matt Parrish

๐Ÿ› ๐Ÿ’ป ๐Ÿ“– โš ๏ธ

Justin Hall

๐Ÿ“ฆ

Anto Aravinth

๐Ÿ’ป โš ๏ธ ๐Ÿ“–

Jonah Moses

๐Ÿ“–

ลukasz Gandecki

๐Ÿ’ป โš ๏ธ ๐Ÿ“–

Ivan Babak

๐Ÿ› ๐Ÿค”

Jesse Day

๐Ÿ’ป

Ernesto Garcรญa

๐Ÿ’ฌ ๐Ÿ’ป ๐Ÿ“–

Josef Maxx Blake

๐Ÿ’ป ๐Ÿ“– โš ๏ธ

Michal Baranowski

๐Ÿ“ โœ…

Arthur Puthin

๐Ÿ“–

Thomas Chia

๐Ÿ’ป ๐Ÿ“–

Thiago Galvani

๐Ÿ“–

Christian

โš ๏ธ

Alex Krolick

๐Ÿ’ฌ ๐Ÿ“– ๐Ÿ’ก ๐Ÿค”

Johann Hubert Sonntagbauer

๐Ÿ’ป ๐Ÿ“– โš ๏ธ

Maddi Joyce

๐Ÿ’ป

Ryan Vice

๐Ÿ“–

Ian Wilson

๐Ÿ“ โœ…

Daniel

๐Ÿ› ๐Ÿ’ป

Giorgio Polvara

๐Ÿ› ๐Ÿค”

John Gozde

๐Ÿ’ป

Sam Horton

๐Ÿ“– ๐Ÿ’ก ๐Ÿค”

Richard Kotze (mobile)

๐Ÿ“–

Brahian E. Soto Mercedes

๐Ÿ“–

Benoit de La Forest

๐Ÿ“–

Salah

๐Ÿ’ป โš ๏ธ

Adam Gordon

๐Ÿ› ๐Ÿ’ป

Matija Marohniฤ‡

๐Ÿ“–

Justice Mba

๐Ÿ“–

Mark Pollmann

๐Ÿ“–

Ehtesham Kafeel

๐Ÿ’ป ๐Ÿ“–

Julio Pavรณn

๐Ÿ’ป

Duncan L

๐Ÿ“– ๐Ÿ’ก

Tiago Almeida

๐Ÿ“–

Robert Smith

๐Ÿ›

Zach Green

๐Ÿ“–

dadamssg

๐Ÿ“–

Yazan Aabed

๐Ÿ“

Tim

๐Ÿ› ๐Ÿ’ป ๐Ÿ“– โš ๏ธ

Divyanshu Maithani

โœ… ๐Ÿ“น

Deepak Grover

โœ… ๐Ÿ“น

Eyal Cohen

๐Ÿ“–

Peter Makowski

๐Ÿ“–

Michiel Nuyts

๐Ÿ“–

Joe Ng'ethe

๐Ÿ’ป ๐Ÿ“–

Kate

๐Ÿ“–

Sean

๐Ÿ“–

James Long

๐Ÿค” ๐Ÿ“ฆ

Herb Hagely

๐Ÿ’ก

Alex Wendte

๐Ÿ’ก

Monica Powell

๐Ÿ“–

Vitaly Sivkov

๐Ÿ’ป

Weyert de Boer

๐Ÿค” ๐Ÿ‘€ ๐ŸŽจ

EstebanMarin

๐Ÿ“–

Victor Martins

๐Ÿ“–

Royston Shufflebotham

๐Ÿ› ๐Ÿ“– ๐Ÿ’ก

chrbala

๐Ÿ’ป

Donavon West

๐Ÿ’ป ๐Ÿ“– ๐Ÿค” โš ๏ธ

Richard Maisano

๐Ÿ’ป

Marco Biedermann

๐Ÿ’ป ๐Ÿšง โš ๏ธ

Alex Zherdev

๐Ÿ› ๐Ÿ’ป

Andrรฉ Matulionis dos Santos

๐Ÿ’ป ๐Ÿ’ก โš ๏ธ

Daniel K.

๐Ÿ› ๐Ÿ’ป ๐Ÿค” โš ๏ธ ๐Ÿ‘€

mohamedmagdy17593

๐Ÿ’ป

Loren โ˜บ๏ธ

๐Ÿ“–

MarkFalconbridge

๐Ÿ› ๐Ÿ’ป

Vinicius

๐Ÿ“– ๐Ÿ’ก

Peter Schyma

๐Ÿ’ป

Ian Schmitz

๐Ÿ“–

Joel Marcotte

๐Ÿ› โš ๏ธ ๐Ÿ’ป

Alejandro Dustet

๐Ÿ›

Brandon Carroll

๐Ÿ“–

Lucas Machado

๐Ÿ“–

Pascal Duez

๐Ÿ“ฆ

Minh Nguyen

๐Ÿ’ป

LiaoJimmy

๐Ÿ“–

Sunil Pai

๐Ÿ’ป โš ๏ธ

Dan Abramov

๐Ÿ‘€

Christian Murphy

๐Ÿš‡

Ivakhnenko Dmitry

๐Ÿ’ป

James George

๐Ÿ“–

Joรฃo Fernandes

๐Ÿ“–

Alejandro Perea

๐Ÿ‘€

Nick McCurdy

๐Ÿ‘€ ๐Ÿ’ฌ

Sebastian Silbermann

๐Ÿ‘€

Adriร  Fontcuberta

๐Ÿ‘€ ๐Ÿ“–

John Reilly

๐Ÿ‘€

Michaรซl De Boey

๐Ÿ‘€ ๐Ÿ’ป

Tim Yates

๐Ÿ‘€

Brian Donovan

๐Ÿ’ป

Noam Gabriel Jacobson

๐Ÿ“–

Ronald van der Kooij

โš ๏ธ ๐Ÿ’ป

Aayush Rajvanshi

๐Ÿ“–

Ely Alamillo

๐Ÿ’ป โš ๏ธ

Daniel Afonso

๐Ÿ’ป โš ๏ธ

Laurens Bosscher

๐Ÿ’ป

Sakito Mukai

๐Ÿ“–

Tรผrker Teke

๐Ÿ“–

Zach Brogan

๐Ÿ’ป โš ๏ธ

Ryota Murakami

๐Ÿ“–

Michael Hottman

๐Ÿค”

Steven Fitzpatrick

๐Ÿ›

Juan Je Garcรญa

๐Ÿ“–

Championrunner

๐Ÿ“–

Sam Tsai

๐Ÿ’ป โš ๏ธ ๐Ÿ“–

Christian Rackerseder

๐Ÿ’ป

Andrei Picus

๐Ÿ› ๐Ÿ‘€

Artem Zakharchenko

๐Ÿ“–

Michael

๐Ÿ“–

Braden Lee

๐Ÿ“–

Kamran Ayub

๐Ÿ’ป โš ๏ธ

Matan Borenkraout

๐Ÿ’ป

Ryan Bigg

๐Ÿšง

Anton Halim

๐Ÿ“–

Artem Malko

๐Ÿ’ป

Gerrit Alex

๐Ÿ’ป

Karthick Raja

๐Ÿ’ป

Abdelrahman Ashraf

๐Ÿ’ป

Lidor Avitan

๐Ÿ“–

Jordan Harband

๐Ÿ‘€ ๐Ÿค”

Marco Moretti

๐Ÿ’ป

sanchit121

๐Ÿ› ๐Ÿ’ป

Solufa

๐Ÿ› ๐Ÿ’ป

Ari Perkkiรถ

โš ๏ธ

This project follows the all-contributors specification. Contributions of any kind welcome!

LICENSE

MIT

Comments
  • [5.5.0] Getting warning about

    [5.5.0] Getting warning about "act" anyway

    Thanks for the fast work Kent, but seems something is still off. I've updated to 5.5.0 and tests are still generating same act warnings. Am I missing something here? Do we need to actually use act inside the tests?

    https://travis-ci.org/mobxjs/mobx-react-lite/builds/489613981

    It's curious that I've actually removed a bunch of flushEffects calls which were necessary before and tests are passing just fine. Clearly act helped with that. And yet those warnings shouldn't be there. ๐Ÿค”

    released 
    opened by danielkcz 128
  • fix(typescript): move typings to DefinitelyTyped

    fix(typescript): move typings to DefinitelyTyped

    See #436, https://github.com/testing-library/dom-testing-library/pull/337

    Remove the TypeScript typedefs from this repo in favor of having the community maintain them at DefinitelyTyped.

    Why

    There are no core teammembers with the TS knowledge needed to maintain the types, and they are not well tested or integrated with the codebase.


    See also https://github.com/reduxjs/redux/issues/3500

    TypeScript released 
    opened by alexkrolick 96
  • feat: Add `renderHook`

    feat: Add `renderHook`

    What:

    Imlement minimal renderHook from @testing-library/react-hooks

    Why:

    @testing-library/react-hooks is not compatible with React 18 and it's questionable if certain APIs will make sense in React 18. This ensures that the supported version of React that is used with your Testing Library APIs is always consistent.

    error testing: We don't have this solved in @testing-library/react. It should be solved in the renderer testing library. suspense: Can be solved with wrapper waitForNextUpdate: Use waitFor instead. When an update is triggered and what is part of an update is not always clear and in 99% of the cases (even if hooks relying on data e.g. apollo-client) not relevant. See https://github.com/eps1lon/apollo-client/pull/1/

    How:

    Implement minimal renderHook with just rerender, rerender and unmount. Assertions are made on the committed result not the render result. Renders are not something to test for since they're ultimately not detereministic depending on the component implementation. However, we don't want to test component implementation details.

    For more granular testing one could always create a custom test component around the hook under test and pass it to our render. This has always been the recommended approach anyway. But it requires more writing and instead of insisting that this is bad practice we meet devs halfway, provide a render wrapper around creating a test component but then reduce the API of that render wrapper.

    If your goal was to count renders then React.Profiler is the better approach anyway.

    Checklist:

    • [x] Documentation added to the docs site: https://github.com/testing-library/testing-library-docs/pull/967
    • [x] Tests
    • [x] TypeScript definitions updated
    • [x] Ready to be merged
    enhancement released 
    opened by eps1lon 54
  • Support for React 18

    Support for React 18

    Describe the feature you'd like:

    It's probably premature, given experimental nature of Concurrent mode. but I might as we start the discussion.

    Perhaps I am misunderstanding something, but I think it would be useful if tests would run in Concurrent mode to mimic real app behavior as close as possible.

    At this point, it's probably about replacing ReactDOM.render with ReactDOM.createRoot.

    The question is how to make it in a compatible way so people can decide which version to use without polluting actual test files with it.

    Suggested implementation:

    Probably the most obvious choice is exposing function renderConcurrent which would be fine for the experimental phase. However, given that Concurrent will most likely become a "new normal" eventually, it would be kinda weird to have that in tests.

    Perhaps the env variable might be better approach ultimately. It's easy to switch and doesn't need to pollute actual test files with it.

    Describe alternatives you've considered:

    Publishing major version when Concurrent mode is official and stable and keep rolling in that direction only. An obvious drawback is that people would need to stick to the previous major as long as they are testing against code that doesn't support Concurrent mode.

    opened by danielkcz 42
  • on change for Material UI Select component not triggered

    on change for Material UI Select component not triggered

    • react-testing-library version: 4.1.3
    • react version: 16.4.1
    • node version: 11.10.1
    • npm (or yarn) version: 6.7.0

    Relevant code or config:

        const select = await waitForElement(() =>
          getByTestId("select-testid")
        );
    
        select.value = "testValue";
        fireEvent.change(select);
    
       <Select
           className={classes.select}
           onChange={this.handleSelectChange}
           value={selectedValue}
           inputProps={{
             id: "select-id",
             "data-testid": "select-id"
           }}
       >
    

    What you did:

    I am trying to fire the onChange method of the Material UI Select.

    What happened:

    onChange won't fire. Also tried with

    select.dispatchEvent(new Event('change', { bubbles: true }));
    
    opened by dimosmera 41
  • How to test React.Portal

    How to test React.Portal

    react-testing-library: 2.1.1 node: 8.9.3 yarn: 1.6.0

    import React from "react";
    import { render, Simulate } from "react-testing-library";
    
    import Button from "material-ui/Button";
    import Dialog, {
      DialogActions,
      DialogContent,
      DialogTitle
    } from "material-ui/Dialog";
    
    export const CommonDialog = props => {
      const { body, children, hideModal, isVisible, title } = props;
      return (
        <Dialog open={isVisible}>
          <DialogTitle>{title}</DialogTitle>
          <DialogContent>
            {body}
            {children}
          </DialogContent>
          <DialogActions>
            <Button id="close" onClick={hideModal}>
              Close
            </Button>
          </DialogActions>
        </Dialog>
      );
    };
    
    test("render dialog", () => {
      const mockCallback = jest.fn();
      const { getByText, getByTestId, container } = render(
        <CommonDialog title="test" isVisible={true} hideModal={mockCallback} />
      );
      Simulate.click(getByText("Close"));
      expect(mockCallback).toBeCalled();
      expect(container).toMatchSnapshot();
    });
    

    in the snapshot, it is just a simple div, and the Close button could not be found. It is not immediately not obvious what's went wrong here. I was using enzyme and it is working fine.

    question 
    opened by bugzpodder 40
  • Add getById method to render exports

    Add getById method to render exports

    Describe the feature you'd like:

    For many apps the labels of elements are subject to the most potential change and volatility. In many cases makes much more sense to reference by id f.ex when developing i18n apps.

    Suggested implementation:

    getByTestId a shortcut to container.querySelector([data-testid="${yourId}"])

    Simply add getById a shortcut to container.querySelector([id="${yourId}"])

    Teachability, Documentation, Adoption, Migration Strategy:

    Provide whatever docs to recommend it in some cases while not in others. I generally disagree with using text labels to reference HTML items as they are the most volatile in any app so it defeats the purpose IMO (+20 years web dev experience). But whatever rocks your boat.

    Cheers.

    opened by kristianmandrup 37
  • scheduleFn is calling NormalPriority as a function rather than cb

    scheduleFn is calling NormalPriority as a function rather than cb

    As of https://github.com/testing-library/react-testing-library/pull/732/files we're seeing:

    	TypeError: callback is not a function
    	    at <Jasmine>
    	    at scheduleFn (webpack:///node_modules/@testing-library/react/dist/@testing-library/react.esm.js:230:1 <- tests.webpack.js:27483:12)
    	    at scheduleCallback (webpack:///node_modules/@testing-library/react/dist/@testing-library/react.esm.js:232:1 <- tests.webpack.js:27485:46)
    	    at Object.then (webpack:///node_modules/@testing-library/react/dist/@testing-library/react.esm.js:245:1 <- tests.webpack.js:27498:9)
    

    Looking at that PR it seems to have two sources of truth: isModernScheduleCallbackSupported based on the react version and NormalPriority based on the existence of Scheduler.

    isModernScheduleCallbackSupported seems to be true yet Scheduler undefined.

    Which causes it to call scheduleFn(NormalPriority, cb) rather than scheduleFn(cb). And scheduleFn is callback => callback().

    released 
    opened by lerouxb 35
  • Add getById and getByClass

    Add getById and getByClass

    Querying by id and classes is the Hello World of the frontend querying and the library doesn't allow that for now.

    What about creating the getById and getByClass on the tests?

    Restricting the frontend id querying is not improving, it is quite the opposite, what is really does is decrease the capacity of the library.

    Placing a lot of data-testids on the code pollutes it, because it places unnecessary tags on html codes in terms of code functionality. The code becomes polluted with tags only related for testing.

    I am in favor of TDDs, but adding things in the code (or worse: on html tags) only for testing is exaggerated. A good TDD will improve the code with more organization! A bad TDD will add things on code only related for testing purposes.

    Some people can argue and defend the usage of data-testids on the code for whatever reason, but what I find uncomfortable is to disable for everybody the most basic querying on DOM elements.

    opened by Victorcorcos 34
  • Fix build for React next

    Fix build for React next

    Not sure exactly how/when this happened, but the build is failing: https://travis-ci.org/github/testing-library/react-testing-library/builds/703268660

    Help welcome!

    bug released 
    opened by kentcdodds 33
  • useEffect not triggering inside jest

    useEffect not triggering inside jest

    • react-testing-library version: 5.2.3
    • react version: 16.7.0-alpha.0
    • node version: CodeSandbox
    • npm (or yarn) version: CodeSandbox

    Relevant code or config:

      let a = false;
      function Test() {
        React.useEffect(() => {
          a = true;
        });
        return <div>Hello World</div>;
      }
      render(<Test />);
      expect(a).toBe(true);
    

    What you did:

    I'm trying to test functions with the useEffect hook inside jest.

    What happened:

    The useEffect hook is not executed correctly inside a jest environment after calling render(<Test />). However it appears to be working correctly if it is called directly in a browser environment.

    Reproduction:

    Working example: https://codesandbox.io/s/l947z8v6xq (index.js) Not working example in jest: https://codesandbox.io/s/7k5oj92740 (index.test.js)

    Problem description:

    The useEffect hook should have been executed after the render call

    enhancement 
    opened by peterjuras 32
  • FakeTimes problem when upgrading jest 25 to 29

    FakeTimes problem when upgrading jest 25 to 29

    Hi, everyone! I have several problems when upgrading jest 25 to 29 (Problem on faketimers)

    Installed dependencies

    "react": "16.13.1", "react-dom": "16.13.1",

    "@testing-library/react-hooks": "^7.0.2", "@testing-library/jest-dom": "5.16.5", "@testing-library/react": "12.1.5", "@types/jest": "28.1.1", "@types/react": "^17.0.33", "jest": "29.2.2", "jest-environment-jsdom": "^29.2.2", "jest-junit": "^12.0.0", "typescript": "4.3"

    Jest.config image

    When using fake timers i have to set legacy to true and the advanceTimers going to works, but it's not work in another test Example :

    image On this code advanceTimers not works fine, at some cases there are a few tests that we need to raise the timeout duration, is there any explanation or something ?

    image If you have any suggestions for my problem, it's going to help me a lot. Thank you

    opened by Okyaaa 0
  • getByText not working for multiline text

    getByText not working for multiline text

    Using multiline text in getByText fails. Is there a workaround for this?

    Failing test

    const exampleText = `
    hello
    
    world
    `
    
    const textElement = screen.getByText(
      exampleText.slice(0, 10),
      { exact: false }
    );
    console.info(textElement.textContent === exampleText); // == True
    expect(screen.getByText(exampleText)).toBeInTheDocument(); // == Fail
    

    Passing test

    const exampleText = `hello world`
    
    const textElement = screen.getByText(
      exampleText.slice(0, 10),
      { exact: false }
    );
    console.info(textElement.textContent === exampleText); // == True
    expect(screen.getByText(exampleText)).toBeInTheDocument(); // == Pass
    
    opened by sbland 1
  • issue in react testing library + MSW+ Redux + Thunk

    issue in react testing library + MSW+ Redux + Thunk

    Hello facing issue in react testing library + MSW+ Redux + Thunk

    Could you please check All details https://github.com/reduxjs/react-redux/issues/1975

    opened by nitinmagdumvista 0
  • Filter by description on findByLabel for password input tests

    Filter by description on findByLabel for password input tests

    Is your feature request related to a problem? Please describe.

    I am trying to test that the inputs in my form have correct inline validation errors set as aria descriptions. This works great when the input is simply a textbox:

    <Label>
      Email
      <input type="text' aria-describedby="emailError" />
    </Label>
    <div id="emailError">Please enter a valid email address</div>
    
    ...
    
    expect(findbyRole('textbox', {
        name: 'Email',
        description: 'Please enter a valid email'
    })).toBeInTheDocument();
    

    However, when the input is a password since it has no role I cannot use the description field on getByRole to find the element.

    Describe the solution you'd like

    This issue recommends using getByLabelText for password inputs, so it would be a lot easier if that query could also search by description.

    <Label>
      Password
      <input type="password' aria-describedby="passwordError" />
    </Label>
    <div id="passwordError">Please enter your password</div>
    
    ...
    
    expect(findByLabelText('Password', {
        description: 'Please enter your password'
    })).toBeInTheDocument();
    

    Describe alternatives you've considered

    Alternatively, if react-testing library could do some magic that means findByRole('password') just works, then that would be a very simple solution and most users probably wouldn't event have to think about it.

    For now my tests merely assert that the error exists in the page and ignore the describedby connection.

    expect(await screen.findByText('Please enter your new password')).toBeInTheDocument();
    

    Additional context Add any other context or screenshots about the feature request here.

    opened by e-compton 1
  • act() now return always a Promise

    act() now return always a Promise

    Description

    Today I update my work project deps, and I noticed that the eslint throws me an error.

    image

    At the beginning I thought that was my mistake, but I checked the code and I found that the error was dispatch because I'm calling act(() => mycode()) as as sync code. I never had this problem before, so I checked my updated types, and I found this export const act: typeof reactAct extends undefined ? (callback: () => void) => void : typeof reactAct, nothing change on testing-library types, but, react-dom updated their types,

    export function act<T>(callback: () => T | Promise<T>): Promise<T>; export function act(callback: () => VoidOrUndefinedOnly): Promise<void>

    on previous versions act had this types

    export function act(callback: () => Promise<void>): Promise<undefined>; export function act(callback: () => VoidOrUndefinedOnly): void;

    Now my question, Will change the act type on testing-library or not?, act is still necessary if we already have the waitFor function?

    Versions

    • react 18.2.0
    • react-dom 18.2.0
    • @types/react 18.0.23 -> 18.0.25
    • @types/react-dom 18.0.7 -> 18.0.9
    • @testing-library/react 13.14.0
    • @testing-library/user-event 14.4.3
    opened by GOI17 4
  • Support `beforeInput` event

    Support `beforeInput` event

    Describe the feature you'd like:

    fireEvent support beforeInput event

    Suggested implementation:

    N/A

    Describe alternatives you've considered:

    N/A

    Teachability, Documentation, Adoption, Migration Strategy:

    N/A

    needs more information 
    opened by zombieJ 2
Releases(v13.4.0)
Owner
Testing Library
The home for all testing-library projects
Testing Library
๐Ÿ”ฎ Proxies nodejs require in order to allow overriding dependencies during testing.

proxyquire Proxies nodejs's require in order to make overriding dependencies during testing easy while staying totally unobtrusive. If you want to stu

Thorsten Lorenz 2.7k Dec 27, 2022
Test spies, stubs and mocks for JavaScript.

Sinon.JS Standalone and test framework agnostic JavaScript test spies, stubs and mocks (pronounced "sigh-non", named after Sinon, the warrior). Compat

Sinon.JS 9.2k Jan 4, 2023
Minimalistic BDD-style assertions for Node.JS and the browser.

Expect Minimalistic BDD assertion toolkit based on should.js expect(window.r).to.be(undefined); expect({ a: 'b' }).to.eql({ a: 'b' }) expect(5).to.be.

Automattic 2.1k Jan 4, 2023
๐Ÿ Simple and complete React DOM testing utilities that encourage good testing practices.

React Testing Library Simple and complete React DOM testing utilities that encourage good testing practices. Read The Docs | Edit the docs Table of Co

Testing Library 17.3k Jan 4, 2023
Hackathon for Social Good 2022 and use your superpowers to create a solution for the social good.

Getting Started with Create React App This project was bootstrapped with Create React App. Available Scripts In the project directory, you can run: np

Laura Diaz 3 Jun 27, 2022
A Very Good Documentation Site created by the Very Good Ventures Team ๐Ÿฆ„

Very Good Docs Site Developed with ?? by Very Good Ventures ?? A Very Good Docs Site created by the Very Good Ventures Team. Generated by the Very Goo

Very Good Open Source 8 Nov 2, 2022
An extension of DOM-testing-library to provide hooks into the shadow dom

Why? Currently, DOM-testing-library does not support checking shadow roots for elements. This can be troublesome when you're looking for something wit

Konnor Rogers 28 Dec 13, 2022
Shikhar 4 Oct 9, 2022
jQuery plugin to encourage strong user passwords

Naked Passwordยถ โ†‘ Simple jQuery plugin to improve security on passwords. Usageยถ โ†‘ Naked password is extremely easy to use. All thats needed is for you

Platform45 307 Nov 3, 2022
This is a Chrome extension that aims to encourage accessibility awareness while using GitHub

github-a11y This is a Google Chrome extension that runs a simple JavaScript snippet on github.com domain and aims to encourage accessibility mindfulne

Kate Higa 9 Jul 24, 2022
Multipurpose entertainment bot that seeks to encourage activity on your server.

Nino ?? Multi-functional discord bot Bot used by 100k users and 300 guilds <3 ?? Features Full Bot It has: English and Spanish language support. Requi

uSebazz 28 Dec 3, 2022
Contented is a Markdown-based authoring workflow that encourage developer authoring within its contextual Git repository.

Contented is a Markdown-based authoring workflow that encourage developer authoring within its contextual Git repository. npm i @birthdayresearch/cont

Birthday Research 44 Jan 7, 2023
Opinionated collection of TypeScript definitions and utilities for Deno and Deno Deploy. With complete types for Deno/NPM/TS config files, constructed from official JSON schemas.

Schemas Note: You can also import any type from the default module, ./mod.ts deno.json import { type DenoJson } from "https://deno.land/x/[email protected]

deno911 2 Oct 12, 2022
๐Ÿ“—๐ŸŒ ๐Ÿšข Comprehensive and exhaustive JavaScript & Node.js testing best practices (August 2021)

?? Why this guide can take your testing skills to the next level ?? 46+ best practices: Super-comprehensive and exhaustive This is a guide for JavaScr

Yoni Goldberg 19.9k Jan 2, 2023
for this repo I'll do some practices(exercices) using Jest for testing my javscript code.

js-testing for this repo I'll do some practices(exercices) using Jest for testing my javscript code. Here are questions for all resolved js Jest testi

Kandy Peter Kamuntu 6 Mar 16, 2022
JavaScript Testing utilities for React

Enzyme Enzyme is a JavaScript Testing utility for React that makes it easier to test your React Components' output. You can also manipulate, traverse,

enzyme - JavaScript Testing utilities for React 20k Dec 28, 2022
A complete habits manager, where you can track your progress and complete each daily activity in an organized way.

TrackIt Habit manager in a dynamic, clear and simple way. TackIt is an application that seeks to make it simple and accessible for any user to control

Rui Neto 13 Dec 31, 2022
A testing focused Remix Stack, that integrates E2E & Unit testing with Playwright, Vitest, MSW and Testing Library. Driven by Prisma ORM. Deploys to Fly.io

Live Demo ยท Twitter A testing focused Remix Stack, that integrates E2E & Unit testing with Playwright, Vitest, MSW and Testing Library. Driven by Pris

Remix Stacks 18 Oct 31, 2022